I am trying to figure out how can we correctly wait until a lock is released in another thread.
I think the code will explain better what do I mean:
myLock.lock();
sendSomewhereMyLock(myLock); //creates new threads inside
myLock.waitUntilReleasedByAnotherThread(60L, TimeUnit.SECONDS);
//do something after the lock is released
I thought that tryLock(long time, TimeUnit unit)
is the method which I need, but Java docs says that the method will be executed immediately because the lock was acquired by current thread:
If the lock is available this method returns immediately with the value true. If the lock is not available then the current thread becomes disabled for thread scheduling purposes and lies dormant until one of three things happens:
- The lock is acquired by the current thread; or
- Some other thread interrupts the current thread, and interruption of lock acquisition is supported; or
- The specified waiting time elapses
What should I use then?
I think what you are looking for is a Condition
With that you can define a condition like workCompleted
and have the initial thread check and wait on that condition.
final Condition workCompleted = myLock.newCondition();
//...
myLock.lock();
try {
final OtherThread otherThread = startOtherThread(myLock, workCompleted);
while (otherThread.completed() == false) {
workCompleted.await();
}
} finally {
myLock.unlock();
}
// other thread
doTheWork();
this.completed = true;
theLock.lock();
try {
workCompleted.signal();
} finally {
theLock.unlock();
}
There are several of such conditions pre-made in the concurrent package, some of them might match your requirements better than the simple example above.
I suggest CountDownLatch
, which is designed exactly for this purpose:
A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.
Example usage:
CountDownLatch latch = new CountDownLatch(1);
new Thread(() -> {
doSomething();
latch.countDown(); // Reaches 0, latch is released
}).start();
latch.await(60L, TimeUnit.SECONDS);
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