首页 > 解决方案 > 关闭执行器服务

问题描述

我正在开发一个应用程序,我不断地从 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());
        }
    }

标签: javaexecutorserviceexecutor

解决方案


关闭您的ExecutorService. 您应该注意两种关闭类型,shutdown()shutdownNow()

如果您在使用 Java EE 的应用服务器上运行应用程序,您还可以使用ManagedExecutorService,它由框架管理并会自动关闭。


推荐阅读