我试图持有期货的静态列表,并在稍后时间取消()或通知()正在进行的期货。与这些期货相关的Callable类在其中有一个wait(),所以每一个必须由外部来源通知才能继续。但是,我的notify()调用似乎被忽略,因为可调用对象从未超过其等待语句。与期货的列表中的类看起来是这样的:使用期货图谱,我如何通知()一个单一的元素?
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!
}
}
}
}
}
可调用的类只是现在一个样机,类似于这样:
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;
}
的notify()方法被调用,但似乎没有效果。 Future的对象引用显示有效(即局部变量“future”与存储在静态列表中的未来引用相匹配)。
我可能在这里错过了一些并发性的基本概念,但我期望当condition2满足时,我的Callable将继续执行wait()调用。
请注意,如果我使用cancel()而不是notify(),它会中断我的runnable并导致InterruptedException,如我所料。
你究竟在努力做什么? –
这是针对客户端发起的报告请求期间的Web应用程序。在我的call()方法中,一个长时间运行的查询被调用(在“在这里做一些工作”部分)。这个查询将超过我们的TCP连接超时,所以它必须是异步的。一旦查询准备好返回,我等待()直到客户端接下来轮询报告(每10秒检查一次报告是否准备就绪)。然后我附加客户端的输出流(在wait()期间),并写入它,现在有查询的结果(在“做其他工作”部分)。那有意义吗? –