Search code examples
javamultithreadingjava.util.concurrent

How to have one java thread wait for the result of another thread?


I frequently need to have a thread wait for the result of another thread. Seems like there should be some support for this in java.util.concurrent, but I can't find it.

Exchanger is very close to what I'm talking about, but it's bi-directional. I only want Thread A to wait on Thread B, not have both wait on each other.

Yes, I know I can use a CountDownLatch or a Semaphore or Thread.wait() and then manage the result of the computation myself, but it seems like I must be missing a convenience class somewhere.

What am I missing?

UPDATE

// An Example which works using Exchanger
// but you would think there would be uni-directional solution
protected Exchanger<Integer> exchanger = new Exchanger<Integer>();

public void threadA() {
    // perform some computations
    int result = ...;

    exchanger.exchange(result);
}


public void threadB() {

    // retrieve the result of threadA
    int resultOfA = exchanger.exchange(null);
}

Solution

  • So far, it seems like BlockingQueue may be the best solution I've found.

    eg.

    BlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(1);
    

    The waiting thread will call queue.take() to wait for the result, and the producing queue will call queue.add() to submit the result.