Implement a blocking function call in Java
If you're waiting on a specific object, you can call myObject.wait()
with one thread, and then wake it up with myObject.notify()
or myObject.notifyAll()
. You may need to be inside a synchronized
block:
class Example {
List list = new ArrayList();
// Wait for the list to have an item and return it
public Object getFromList() {
synchronized(list) {
// Do this inside a while loop -- wait() is
// not guaranteed to only return if the condition
// is satisfied -- it can return any time
while(list.empty()) {
// Wait until list.notify() is called
// Note: The lock will be released until
// this call returns.
list.wait();
}
return list.remove(0);
}
}
// Add an object to the list and wake up
// anyone waiting
public void addToList(Object item) {
synchronized(list) {
list.add(item);
// Wake up anything blocking on list.wait()
// Note that we know that only one waiting
// call can complete (since we only added one
// item to process. If we wanted to wake them
// all up, we'd use list.notifyAll()
list.notify();
}
}
}
There are a couple of different approaches and primitives available, but the most appropriate sounds like a CyclicBarrier or a CountDownLatch.
You can use a CountDownLatch.
latch = new CountDownLatch(1);
To block, call:
latch.await();
To unblock, call:
latch.countDown();