【发布时间】:2017-12-01 19:01:49
【问题描述】:
我的代码如下:
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;
}
我正在从其他类调用此服务以获得未来:
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() 的结果中检查当前正在运行的线程时,我仍然可以找到未来执行的线程。
【问题讨论】:
-
获取未来值后,有没有查看当前运行的线程?
-
是的,
shutDown()是正确的。没有线程泄漏。您可能会看到线程停留了一段时间,但如果这可能导致线程泄漏,那将是一个重大错误。 -
@efekctive 是的,我已经更新了代码以避免混淆。
-
@Kayaman doe 在调用 future.get() 之前调用 executorService.shutDown() 保证它不会中断未来任务的执行?我很困惑,因为 shutdown 的文档指出“此方法不会等待先前提交的任务完成执行。”
-
就是这样。如果有泄漏,您会立即注意到
标签: java multithreading java-threads