[英]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;
}
我从其他班级调用此服务来获得未来:
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)
,这将确保不会出现线程泄漏?
注意,当我在Thread.getAllStackTraces()
的结果中检查当前正在运行的线程时调用future.cancel(true)
,我仍然可以找到未来执行的线程。
你问的是错误的问题!
在方法中创建服务然后将其丢弃就没有意义。
创建该服务实例并非免费提供。 这种抽象的整个想法是确保有效利用基础设施元素!
换句话说:退后一步,重新设计你的设计; 所以这个服务成为某个类的领域 ,例如! 是的,这可能会变得复杂。 但最有可能的是,与继续你问题中显示的方法相比,在那个角落花费时间会花更多的钱。
现在出了executorService.shutDown()和future.cancel(true),这将确保不会出现线程泄漏?
没有一个。
executorService.shutdown()将继续运行当前任务并拒绝新提交的任务。
如果当前正在运行,则future.cancel(true)将中断相应的任务(但是您负责检查任务是否被中断并尽快完成任务的执行)
注意,当我在Thread.getAllStackTraces()的结果中检查当前正在运行的线程时调用future.cancel(true)后,我仍然可以找到未来执行的线程。
正如我之前提到的,future.cancel(true)不会停止该线程。 它只发送一个中断。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.