我正在开发一个应用程序,在其中我不断从Kafka主题读取数据。这些数据以字符串格式出现,然后我将其写入xml文件并将其存储在硬盘上。现在,这些数据是随机产生的,并且大多数情况下应该是连续快速地散装的。
要写入这些文件,我正在使用执行器服务。
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,但是我的应用程序应该可以连续运行。
如果出现任何异常,我的整个应用程序都被杀死,会自动关闭我的执行器吗? 还是应该像上面在代码中所做的那样,捕获未检查的异常并关闭执行器? 我可以选择不显式关闭代码中的执行器吗?我有什么选择?
It is a good practice to shut down your
ExecutorService
. There are two types of shutdown, shutdown() and shutdownNow().If you're running you application on an application server with Java EE, you can also use a ManagedExecutorService, which is managed by the framework and will be shut down automatically.