开发者

Implement a blocking function call in Java

What is the recommended / best way to implement a blocking function call in Java, that can be la开发者_StackOverflow社区ter 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();


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜