Reputation: 2980
I have a Spring boot application which has Hazelcast for caching in it. When multiple instances are clustered with Hazelcast, I am having this exception on the unlock operation:
java.lang.IllegalMonitorStateException: Current thread is not owner of the lock! -> Owner: 33ce48f8-dda3-471f-abae-994d25dcc030, thread ID: 55
at com.hazelcast.concurrent.lock.operations.UnlockOperation.unlock(UnlockOperation.java:75) ~[hazelcast-3.11.4.jar!/:3.11.4]
at com.hazelcast.concurrent.lock.operations.UnlockOperation.run(UnlockOperation.java:64) ~[hazelcast-3.11.4.jar!/:3.11.4]
at com.hazelcast.spi.Operation.call(Operation.java:170) ~[hazelcast-3.11.4.jar!/:3.11.4]
at com.hazelcast.spi.impl.operationservice.impl.OperationRunnerImpl.call(OperationRunnerImpl.java:208) [hazelcast-3.11.4.jar!/:3.11.4]
at com.hazelcast.spi.impl.operationservice.impl.OperationRunnerImpl.run(OperationRunnerImpl.java:197) [hazelcast-3.11.4.jar!/:3.11.4]
at com.hazelcast.spi.impl.operationservice.impl.OperationRunnerImpl.run(OperationRunnerImpl.java:413) [hazelcast-3.11.4.jar!/:3.11.4]
at com.hazelcast.spi.impl.operationexecutor.impl.OperationThread.process(OperationThread.java:153) [hazelcast-3.11.4.jar!/:3.11.4]
at com.hazelcast.spi.impl.operationexecutor.impl.OperationThread.process(OperationThread.java:123) [hazelcast-3.11.4.jar!/:3.11.4]
at com.hazelcast.spi.impl.operationexecutor.impl.OperationThread.run(OperationThread.java:110) [hazelcast-3.11.4.jar!/:3.11.4]
Here is my component where I do locking and unlocking operations:
package com.companyname.service.servicename.job;
import com.hazelcast.core.ILock;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class UpdateRaceCacheJob {
@Scheduled(fixedDelay = 10000)
public void updateRaceCache() {
ILock lock = hazelcastInstance.getLock("race-lock");
try {
if (!lock.tryLock()) {
return;
}
// service calls
} finally {
lock.unlock();
}
}
}
When I replace lock.unlock(); line with:
if (lock.isLockedByCurrentThread()) {
lock.unlock();
}
I get a warning from sonar: Unlock this lock along all executions paths of this method.
Thank you!
Upvotes: 3
Views: 8930
Reputation: 591
Since Hazelcast locks are distributed, they are protected by thread ownership so that only the thread who locked it can unlock.
In your code, you use tryLock
which may return false
. However, finally
block executes unlock operation in any case. So, each time you can't get the lock (because it is locked by some other thread in the cluster), you will try to unlock it and you will get that exception.
It is a good idea to use lock.isLockedByCurrentThread()
to check the ownership.
Upvotes: 7