确定当前在ExecutorService中运行的Callables

时间:2012-09-13 21:04:21

标签: java multithreading executorservice callable

我希望能够获得我submit到目前正在进行的ExecutorService(特别是ThreadPoolExecutor)的Callables(因此它们不能通过getQueue()获得)。

我尝试创建一个子类来覆盖beforeExecute,但是那里给出的Runnable是FutureTask,而不是提交的原始Callable。

还有另一种方法可以确定活动的Callables吗?


最终,我想对这些信息做两件事:

  1. 获取正在运行的任务,以便它们可以显示在用户界面中
  2. 检查Callable引用的文件是否与模式匹配,如果匹配,则取消它

2 个答案:

答案 0 :(得分:5)

您可以覆盖AbstractExecutorService.newTaskFor(),它可以让您访问原始RunnableCallable。然后用跟踪装饰器装饰它们并传递给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);
    }

    ...
}