Implement a blocking function call in Java

mikera picture mikera · Oct 12, 2011 · Viewed 17.3k times · Source

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.

Answer

Simon Nickerson picture Simon Nickerson · Oct 12, 2011

You can use a CountDownLatch.

latch = new CountDownLatch(1);

To block, call:

latch.await();

To unblock, call:

latch.countDown();