I'm attempting to hold a static list of Futures, and at a later time either cancel() or notify() the Futures which are in progress. The Callable class which is associated with these Futures has a wait() within it, so each one must be notified by an outside source to continue. However, my calls to notify() appear to be ignored, as the callables never get past their wait statement. The class with the list of Futures looks something like this:
private static Map <String, Future<Object>> results = new HashMap <String, Future<Object>>();
ExecutorService taskExecutor;
public void doStuff() {
taskExecutor = Executors.newCachedThreadPool();
// loop inifinitely - external processes will modify the conditions within
while(!shutItDown) {
if (<condition1>) {
// condition 1 dictates the kick-off of a new callable
Future<Object> future = taskExecutor.submit(new MyCallable(id));
results.put(id, future);
}
else if (<condition2>) {
// condition 2 represents a callable in a wait status needs
// to be notified
Future<Object> future = results.get(uid);
if (future != null) {
synchronized(future) {
future.notify(); // this doesn't have the desired effect!
}
}
}
}
}
The Callable class is just a mockup for now, looks similar to this:
public class MyCallable implements Callable<Object> {
private String id;
public MyCallable(String id) {
this.id = id;
}
@Override
public Object call() throws Exception {
try {
// do some work here, then wait on outside notification
synchronized(this) {
this.wait(); // never gets past here!!!
}
// do some other work here, once this has been notified
}
catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
The notify() method is called, but seems to have no effect. The object reference for the Future appears valid (i.e. the local variable "future" matches the reference of the future stored in the static list).
I'm probably missing some basic concept of concurrency here, but I expected that when condition2 is met, my Callable would proceed past the wait() call.
Note that if I use cancel() instead of notify(), it interrupts my runnable and causes an InterruptedException as I would expect.