Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/330.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 关闭执行器服务_Java_Executorservice_Executor - Fatal编程技术网

Java 关闭执行器服务

Java 关闭执行器服务,java,executorservice,executor,Java,Executorservice,Executor,我正在开发一个应用程序,不断地从卡夫卡主题中读取数据。这些数据是字符串格式的,然后我将其写入xml文件并存储在硬盘上。现在,这些数据是随机产生的,而且大部分数据应该是成批的,快速连续的 为了编写这些文件,我使用了Executor服务 ExecutorService executor = Executors.newFixedThreadPool(4); /* called multiple times in quick succession */ public void writeContent

我正在开发一个应用程序,不断地从卡夫卡主题中读取数据。这些数据是字符串格式的,然后我将其写入xml文件并存储在硬盘上。现在,这些数据是随机产生的,而且大部分数据应该是成批的,快速连续的

为了编写这些文件,我使用了Executor服务

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();
            }
        }

    }
我想知道我应该什么时候关闭我的executor服务。如果我的应用程序是有时间限制的,我会在executor实例上使用它,但我的应用程序应该持续运行

如果出现任何异常,我的整个应用程序被终止,它会自动关闭我的执行器吗? 或者我应该捕获一个未检查的异常并关闭我的执行器,就像我在代码中所做的那样? 我可以选择不在代码中显式关闭执行器吗?我有什么选择

编辑:因为我的类是@RestController类,所以我使用了以下命令 关闭我的执行者服务的方法


关闭
Executor服务
是一种很好的做法。您应该注意两种类型的关机,以及


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

关闭
ExecutorService
是一种很好的做法。您应该注意两种类型的关机,以及


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

请注意,如果在单独的线程中处理已消耗的记录,则可能会提交尚未处理的记录,因此在重新平衡时有丢失消息的风险。只要有可能,通过向轮询线程中的和进程记录添加更多使用者,可以更轻松地扩展消耗(缺少单词-向组添加更多使用者)请注意,如果在单独的线程中处理已消耗的记录,则可能会提交尚未处理的记录,因此在重新平衡时有丢失消息的风险。只要有可能,通过在轮询线程(缺少单词-将更多使用者添加到组)中的进程和记录中添加更多使用者,可以更轻松地扩展消耗。我使用Executor服务的类是RestController类。所以我认为最好有一个带有PreDestroy注释的destroy()方法,并在那里关闭我的执行器服务。所以我认为最好有一个带有PreDestroy注释的destroy()方法,并在那里关闭我的executor服务。
@PreDestroy
    private void destroy() {
        executor.shutdownNow();
        if(executor != null) {
            System.out.println("executor.isShutdown() = " + executor.isShutdown());
            System.out.println("executor.isTerminated() = " + executor.isTerminated());
        }
    }