How to use hazelcast lock
Asked Answered
M

1

7

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?

Misfile answered 1/10, 2015 at 16:29 Comment(1)
if the post below helped you or answers your question, please accept it as the answer. If you have follow-up questions, feel free to post it too.Syllabub
S
8

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();
}
Syllabub answered 4/10, 2015 at 9:25 Comment(1)
Alternatively tryLock can be used. Like: userClicksStatsCache.tryLock(uuid, USER_CLICK_STATS_TRY_LOCK_TIME_MS, TimeUnit.MILLISECONDS);Ute

© 2022 - 2024 — McMap. All rights reserved.