Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement a blocking function call in Java

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.

like image 318
mikera Avatar asked Oct 12 '11 04:10

mikera


2 Answers

You can use a CountDownLatch.

latch = new CountDownLatch(1);

To block, call:

latch.await();

To unblock, call:

latch.countDown();
like image 171
Simon Nickerson Avatar answered Oct 17 '22 14:10

Simon Nickerson


There are a couple of different approaches and primitives available, but the most appropriate sounds like a CyclicBarrier or a CountDownLatch.

like image 28
Brian Kelly Avatar answered Oct 17 '22 15:10

Brian Kelly