views:

529

answers:

3

I have a problem where I need to synchronize processing for multiple threads across multiple different servers for a Java service on Windows.

In this application, I have multiple consumer threads pullings messages off the same JMS queue. Messages come in in groups of 3 or 4, and I need to make sure the messages in each group are processed completely in serial. I need some sort of synch mechanism to make sure if thread1 pulls a message off, then thread2 pulls the next message from that group, thread2 waits for thread1 to finish processing before starting to process it's message.

Any suggestions on distributed synching mechanisms for threads? Any type of solution would be good (JMS solutions, distributed caching, etc.)

Note: the JMS provider we're using is ActiveMQ.

+6  A: 

ActiveMQ has support for message groups which, quite literally, should be exactly what you need.

andri
I've looked at those briefly. Do you know what happens with the messages groups if you're continuously creating new groups? Would the internal hash continuously grow? Is there a way to "delete" or "expire" a group, so that the group doesn't just sit in memory forever? Thx for the answer, btw.
Andy White
You can close message groups (it's detailed on the page I linked). I'm not sure about the overhead of creating new groups, though -- it's probably to check how that's done straight from the source.
andri
+1  A: 

Is there anything like a group ID in the message headers? If so, a consumer could create a Selector to process the group in sequence.

The assignment of a group to a particular consumer could be done by hashing the group identifier, or they could actively coordinate with each other using some consensus protocol like Paxos or virtual synchrony (with the messages being sent over a separate queue).

erickson
Each group does have a "group ID" field, that can be used to group them all. However, this group ID is coming from an external party, so the consumers won't know the ID until they get the first message.
Andy White
Not sure if that gives you any useful info. I'm sort of an intermediate JMS user, so I haven't worked w/ selectors yet.
Andy White
+2  A: 

you might want to consider using Hazelcast distributed locks. Super lite, easy and open source.

java.util.concurrent.locks.Lock lock = Hazelcast.getLock ("mymonitor");
lock.lock ();
try {
// do your stuff
}finally {
   lock.unlock();
}

Regards,

-talip

Hazelcast - Open Source Distributed Queue, Map, Set, List, Lock

Talip Ozturk