清理使用 ExecutorService 提交的线程

Cleaning up thread submitted using ExecutorService

我的代码如下:

public Future<String> getFuture() {
  ExecutorService executorService = Executors.newSingleThreadExecutor();
  Future<String> future = executorService.submit(() -> {
    //do something
    return "test string";
  });
  executorService.shutDown(); // is this correct?
  return future;
}

我正在从其他 class 调用此服务以获得未来:

 Future<String> future = getFuture();
 String result = future.get();
 future.cancel(true); // will this assure that there wont be any thread leak?

现在出了executorService.shutDown()future.cancel(true)哪个能保证不会有线程泄漏?

请注意,调用 future.cancel(true) 后,当我在 Thread.getAllStackTraces() 的结果中检查当前 运行 个线程时,我仍然可以找到未来执行的线程。

你问错问题了!

在一个方法中创建一个 服务 然后立即将其丢弃是没有意义的。

创建服务实例不是免费的。这种抽象的整个想法是确保高效使用基础设施元素!

换句话说:退后一步,重新设计;这样这个服务就变成了一个 field of some class 例如!是的,这可能会变得很复杂。但最有可能的是,与继续你的问题中所示的方法相比,花时间在那个角落会得到更多的长期回报。

  • 创建一个执行器然后在每次方法调用时将其丢弃是个坏主意。

Now out of executorService.shutDown() and future.cancel(true) which will assure that there wont be thread leaks?

none 个。
executorService.shutdown() 只会保留 运行 当前任务并拒绝新提交的任务。

future.cancel(true) 如果当前为 运行 将中断相应的任务(但您有责任检查任务是否被中断并尽快完成任务的执行可能)

Note that after calling future.cancel(true) when I check currently running threads in the result of Thread.getAllStackTraces() I can still find the thread where future executed.

正如我之前提到的,future.cancel(true) 不会停止线程。它只发送一个中断。