我希望能够获得我submit
到目前正在进行的ExecutorService(特别是ThreadPoolExecutor)的Callables(因此它们不能通过getQueue()
获得)。
我尝试创建一个子类来覆盖beforeExecute
,但是那里给出的Runnable是FutureTask,而不是提交的原始Callable。
还有另一种方法可以确定活动的Callables吗?
最终,我想对这些信息做两件事:
答案 0 :(得分:5)
您可以覆盖AbstractExecutorService.newTaskFor()
,它可以让您访问原始Runnable
和Callable
。然后用跟踪装饰器装饰它们并传递给super.newTaskFor()
。
答案 1 :(得分:1)
as suggested by axtavt我创建了FutureTask
的子类:
public class FutureCallable<V> extends FutureTask<V> {
private Callable<V> callable;
public FutureCallable(Callable<V> callable) {
super(callable);
this.callable = callable;
}
public Callable<V> getCallable() {
return callable;
}
}
并在我的ThreadPoolExecutor
子类中覆盖了一些方法:
public class CustomThreadPoolExecutor extends ThreadPoolExecutor {
private Set<FutureCallable<UpdateResult>> running = new HashSet<FutureCallable<UpdateResult>>();
@Override
public <T> FutureCallable<T> newTaskFor(Callable<T> callable) {
return new FutureCallable<T>(callable);
}
@Override
protected void beforeExecute(Thread t, Runnable r) {
FutureCallable<UpdateResult> task = (FutureCallable<UpdateResult>) r;
running.add(task);
}
@Override
protected void afterExecute(Runnable r, Throwable t) {
FutureCallable<UpdateResult> task = (FutureCallable<UpdateResult>) r;
running.remove(task);
}
...
}