让我们使用一个经典的Executor。应用程序的许多部分都使用该执行程序进行某些计算,每个计算都可以取消,为此我可以在执行程序上调用shutdown()shutdownNow()

但是我只想关闭Executor中的部分任务。可悲的是,我无法访问Future对象,它们是计算实现的私有部分(实际上,计算由actor框架jetlang支持)

我想要像Executor包装器这样的东西,我可以将其传递给计算,并且应该由真正的Executor支持。像这样:

// main application executor
Executor applicationExecutor = Executors.newCachedThreadPool();

// starting computation
Executor computationExecutor = new ExecutorWrapper(applicationExecutor);
Computation computation = new Computation(computationExecutor);
computation.start();

// cancelling computation
computation.cancel();
// shutting down only computation tasks
computationExecutor.shutdown();

// applicationExecutor remains running and happy


还是其他想法?

最佳答案

对于那些想要良好目标的人:最终的解决方案部分基于Ivan Sopov的回答。幸运的是,jetlang仅使用Executor接口(而不是ExecutorService)来运行其任务,因此我创建了包装器类,该类支持停止仅由该包装器创建的任务。

static class StoppableExecutor implements Executor {
    final ExecutorService executor;
    final List<Future<?>> futures = Lists.newArrayList();
    boolean stopped;

    public StoppableExecutor(ExecutorService executor) {
        this.executor = executor;
    }

    void stop() {
        this.stopped = true;
        synchronized (futures) {
            for (Iterator<Future<?>> iterator = futures.iterator(); iterator.hasNext();) {
                Future<?> future = iterator.next();
                if (!future.isDone() && !future.isCancelled()) {
                    System.out.println(future.cancel(true));
                }
            }
            futures.clear();
        }
    }

    @Override
    public void execute(Runnable command) {
        if (!stopped) {
            synchronized (futures) {
                Future<?> newFuture = executor.submit(command);
                for (Iterator<Future<?>> iterator = futures.iterator(); iterator.hasNext();) {
                    Future<?> future = iterator.next();
                    if (future.isDone() || future.isCancelled())
                        iterator.remove();
                }
                futures.add(newFuture);
            }
        }
    }
}


使用它非常简单:

ExecutorService service = Executors.newFixedThreadPool(5);
StoppableExecutor executor = new StoppableExecutor(service);

// doing some actor stuff with executor instance
PoolFiberFactory factory = new PoolFiberFactory(executor);

// stopping tasks only created on executor instance
// executor service is happily running other tasks
executor.stop();


就这样。效果不错。

关于java - Java执行器部分关闭,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7993422/

10-13 05:01