I'm implementing the Future
interface for shared computation. I.e. one thread performs the computation and other threads needed the same result just ask for it through the Future
. So, I've read the Object#wait() method documentation and decided that it perfectly satisfies my needs. Here's how my implementation of the Future#get() method looks:
public class CustomFuture implements Future<Collection<Integer>> {
private AtomicBoolean started;
private Exception computationException;
private boolean cancelled;
private Collection<Integer> computationResult;
private Object waitForTheResult = new Object();
public Collection<Integer> get(){
if(started.compareAndSet(false, true))
//start the computation //notifyAll() is called after finishing the computation here.
while(computationResult == null){
if(cancelled)
throw new CancellationException();
if(computationException != null)
throw new ExectuonException();
synchronized(waitForTheResult){
waitForTheResult.wait();
}
}
return computationResult;
}
//The rest of methods
}
I'm not sure if the implementation is good, because of relying on low-level primitives. I thought that, as a rule of thumb, we should avoid using such a low-level primitives. Maybe that's the case where it's reasonable.
Maybe there's a better alternative of wait()
in java.util.concurrent
.