Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
}
like image 1000
emmby Avatar asked Mar 07 '11 16:03

emmby


2 Answers

Are you looking for Future<T>? That's the normal representation of a task which has (usually) been submitted to a work queue, but may not have completed yet. You can find out its completion status, block until it's finished, etc.

Look at ExecutorService for the normal way of obtaining futures. Note that this is focused on getting the result of an individual task, not rather than waiting for a thread to finish. A single thread may complete many tasks in its life time, of course - that's the whole point of a thread pool.

like image 86
Jon Skeet Avatar answered Sep 18 '22 15:09

Jon Skeet


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.

like image 34
emmby Avatar answered Sep 20 '22 15:09

emmby