Running Non-duplicate Task On A Cluster Using Hazelcast

Having a container cluster is great, but one problem is when you need to run something once only (think table cleanup, pulling data to shared db, etc).

Since you have multiple VM running off the same source code, it will normally run duplicate instance of the task — one per VM. You can avoid that from happening using distributed lock.

 private HazelcatInstance hz;

ILock lock = hz.getLock(MyTask.class.getName());

Every node in the cluster has access to distributed lock. Only one node can obtain the lock. If a node successfully obtained the lock its thread will continue executing, otherwise it will block until it manages to obtain one (or times out).

logger.info("Trying to run task on this node...");
lock.lock(); // thread execution will only pass this line if no other node has the lock

logger.info("Running task on this node..");
// do something here

Since calling lock.lock() might block the thread, you typically want to run it on a separate thread.

If a node that has the lock crashes / dies, the lock will be released, and other nodes can pick it up and become the ‘task owner’.

See Also

Leave a Reply