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?
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With