【问题标题】:Shutting Down Executor Service关闭执行器服务
【发布时间】:2020-05-09 06:37:25
【问题描述】:

我正在开发一个应用程序,我不断地从 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,但我的应用程序应该连续运行。

如果出现任何异常,我的整个应用程序都被杀死了,它会自动关闭我的执行程序吗? 或者我应该像上面在代码中所做的那样捕获未经检查的异常并关闭我的执行程序? 我可以选择不在我的代码中明确关闭我的执行程序吗?我有哪些选择?

编辑:由于我的课程是 @RestController 课程,因此我使用了以下内容 关闭我的执行程序服务的方法

@PreDestroy
    private void destroy() {
        executor.shutdownNow();
        if(executor != null) {
            System.out.println("executor.isShutdown() = " + executor.isShutdown());
            System.out.println("executor.isTerminated() = " + executor.isTerminated());
        }
    }

【问题讨论】:

  • 请注意,如果您在单独的线程中处理已使用的记录,您可能会提交尚未处理的记录,因此存在重新平衡时丢失消息的风险。只要有可能,通过向轮询线程中的和进程记录添加更多消费者来更容易扩展消费
  • (缺少单词 - 向组中添加更多消费者)

标签: java executorservice executor


【解决方案1】:

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

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

【讨论】:

  • 我使用 Executor Service 的类是 RestController 类。所以我认为最好有一个带有 PreDestroy 注释的 destroy() 方法并在那里关闭我的执行程序服务。
猜你喜欢
  • 1970-01-01
  • 2023-03-08
  • 2016-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-16
  • 1970-01-01
相关资源
最近更新 更多