1

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

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

我想要像 Executor wrapper 这样的东西,我可以将它传递给计算,并且应该由真正的 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

还是有其他想法?

4

3 回答 3

2

对于那些想要好的结果的人:有最终的解决方案,部分基于 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();

就这样。效果很好。

于 2011-11-04T17:07:57.287 回答
0

在设置布尔标志之前让你Computation成为一个Runnable(并使用提供的运行)怎么样?Executor类似的东西:

public class Computation
{
  boolean volatile stopped;

  public void run(){
    while(!stopped){
    //do magic
  }

  public void cancel)(){stopped=true;}
}

你正在做的基本上是停止线程。但是,它不会被垃圾收集,而是被重复使用,因为它是由 Executor 管理的。查找“停止线程的正确方法是什么?”。

编辑:请注意,上面的代码非常原始,因为它假设 while 循环的主体需要很短的时间。如果没有,检查将不经常执行,您会注意到取消任务和实际停止之间的延迟。

于 2011-11-03T10:45:36.230 回答
0

像这样的东西?您可以进行部分关闭:

for (Future<?> future : %ExecutorServiceWrapperInstance%.getFutures()) {
    if (%CONDITION%) {
        future.cancel(true);
    }
}

这是代码:

package com.sopovs.moradanen;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class ExecutorServiceWrapper implements ExecutorService {

private final ExecutorService realService;
private List<Future<?>> futures = new ArrayList<Future<?>>();

public ExecutorServiceWrapper(ExecutorService realService) {
    this.realService = realService;
}

@Override
public void execute(Runnable command) {
    realService.execute(command);
}

@Override
public void shutdown() {
    realService.shutdown();

}

@Override
public List<Runnable> shutdownNow() {
    return realService.shutdownNow();
}

@Override
public boolean isShutdown() {
    return realService.isShutdown();
}

@Override
public boolean isTerminated() {
    return realService.isTerminated();
}

@Override
public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
    return realService.awaitTermination(timeout, unit);
}

@Override
public <T> Future<T> submit(Callable<T> task) {
    Future<T> future = realService.submit(task);
    synchronized (this) {
        futures.add(future);
    }
    return future;
}

public synchronized List<Future<?>> getFutures() {
    return Collections.unmodifiableList(futures);
}

@Override
public <T> Future<T> submit(Runnable task, T result) {
    Future<T> future = realService.submit(task, result);
    synchronized (this) {
        futures.add(future);
    }
    return future;
}

@Override
public Future<?> submit(Runnable task) {
    Future<?> future = realService.submit(task);
    synchronized (this) {
        futures.add(future);
    }
    return future;
}

@Override
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) throws InterruptedException {
    List<Future<T>> future = realService.invokeAll(tasks);
    synchronized (this) {
        futures.addAll(future);
    }
    return future;
}

@Override
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)
        throws InterruptedException {
    List<Future<T>> future = realService.invokeAll(tasks, timeout, unit);
    synchronized (this) {
        futures.addAll(future);
    }
    return future;
}

@Override
public <T> T invokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException {
    //don't know what to do here. Maybe this method is not needed by the framework
    //than just throw new NotImplementedException();
    return realService.invokeAny(tasks);
}

@Override
public <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException {
    //don't know what to do here. Maybe this method is not needed by the framework
    //than just throw new NotImplementedException();
    return realService.invokeAny(tasks, timeout, unit);
}
}
于 2011-11-03T11:27:10.297 回答