Implement a blocking function call in Java

18,503

Solution 1

You can use a CountDownLatch.

latch = new CountDownLatch(1);

To block, call:

latch.await();

To unblock, call:

latch.countDown();

Solution 2

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

Solution 3

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();
        }
    }
}
Share:
18,503
mikera
Author by

mikera

Founder of Convex. Clojure hacker, game development, crypto and machine learning enthusiast.

Updated on June 03, 2022

Comments

  • mikera
    mikera almost 2 years

    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.