java - 关闭执行器服务
问题描述
我正在开发一个应用程序,我不断地从 Kafka 主题中读取数据。这些数据采用字符串格式,然后我将其写入 xml 文件并将其存储在硬盘上。现在,这些数据是随机出现的,而且大多数情况下应该是大量的、连续的。
为了编写这些文件,我使用了 Executor Service。
ExecutorService executor = Executors.newFixedThreadPool(4);
/*
called multiple times in quick succession
*/
public void writeContent(String message) {
try {
executor.execute(new FileWriterTask(message));
} catch(Exception e) {
executor.shutdownNow();
e.printStackTrace();
}
}
private class FileWriterTask implements Runnable{
String data;
FileWriterTask(String content){
this.data = content;
}
@Override
public void run() {
try {
String fileName = UUID.randomUUID().toString();
File file = new File("custom path" + fileName + ".xml");
FileUtils.writeStringToFile(file, data, Charset.forName("UTF-8"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
我想知道什么时候应该关闭我的执行程序服务。如果我的应用程序有时间限制,我会在我的执行程序实例上使用 awaitTermination,但我的应用程序应该连续运行。
如果出现任何异常,我的整个应用程序都被杀死了,它会自动关闭我的执行程序吗?或者我应该像上面在代码中所做的那样捕获未经检查的异常并关闭我的执行程序?我可以选择不在我的代码中明确关闭我的执行程序吗?我有哪些选择?
编辑:由于我的课程是 @RestController 课程,我使用以下方式关闭我的执行程序服务
@PreDestroy
private void destroy() {
executor.shutdownNow();
if(executor != null) {
System.out.println("executor.isShutdown() = " + executor.isShutdown());
System.out.println("executor.isTerminated() = " + executor.isTerminated());
}
}
解决方案
关闭您的ExecutorService
. 您应该注意两种关闭类型,shutdown()和shutdownNow()。
如果您在使用 Java EE 的应用服务器上运行应用程序,您还可以使用ManagedExecutorService,它由框架管理并会自动关闭。
推荐阅读
- bash - 使用 csv 在 Bash 中执行 for 循环并在 Internet 上下载文件
- wso2 - WSO2 是 5.11.0 IWA NTLM / KERBEROS
- python - Python数学运算直到按下'n'
- python - /categories 'category' 处的 MultiValueDictKeyError
- javascript - 在 JMeter 中使用预处理器执行 HTTPS 请求
- c# - 显示属性的所有可能的 NullReferenceExceptions
- c# - 在发布版本中的 .net 框架中出现 cors 错误
- android - 将字符串从 onClickListener insde onCreate 传递到外部 onCreate
- flutter - 未来
扑扑,飞镖 - picasa - picasa-desktop : 视频方向问题