Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use hazelcast lock

I have to upgrade an app which is using an old version of hazelcast to one of the more recent versions. There was some hazelcast lock functionality which has since been deprecated and removed altogether from the API. In particular, the old lock functionality worked as such:

Hazecast.getLock(myString);

The getLock function was a static method on Hazelcast. Now it is to be replaced with something like:

hazelcastInstance.getLock(myString);

...where the lock comes from one of the instances in the cluster.

My question is, can I use any one of the instances in the hazelcast cluster to get the lock? And if so, will this lock all instances?

like image 576
user1491636 Avatar asked Oct 01 '15 16:10

user1491636


1 Answers

Q1: Yes, you can use any one of the instances in the hazelcast cluster to get the lock (ILock).

You can think of ILock in hazelcast framework as the distributed implementation of java.util.concurrent.locks.Lock. For more details please see

http://docs.hazelcast.org/docs/3.5/javadoc/com/hazelcast/core/ILock.html

Q2: If you lock the critical section using an ILock, then the guarded critical section is guaranteed to be executed by only one thread in the entire cluster at a given point of time. Thus once the lock() method is called by say Thread1 in one the nodes, other threads (in other nodes as well) will wait until the lock is released.

Sample Code :

HazelcastInstance hazelcastInstance = Hazelcast.newHazelcastInstance();
Lock testLock = hazelcastInstance.getLock( "testLock" );
testLock.lock();
try 
{
   // critical section code.
} 
finally 
{
   testLock.unlock();
}
like image 168
Dinesh Avatar answered Nov 01 '22 02:11

Dinesh