What is the recommended / best way to implement a blocking function call in Java, that can be later unblocked by a call from another thread?
Basically I want to have two methods on an object, where the first call blocks any calling thread until the second method is run by another thread:
public class Blocker {
/* Any thread that calls this function will get blocked */
public static SomeResultObject blockingCall() {
// ...
}
/* when this function is called all blocked threads will continue */
public void unblockAll() {
// ...
}
}
The intention BTW is not just to get blocking behaviour, but to write a method that blocks until some future point when it is possible to compute the required result.
You can use a CountDownLatch.
latch = new CountDownLatch(1);
To block, call:
latch.await();
To unblock, call:
latch.countDown();