Ankit
Ankit

Reputation: 4644

Shutting Down Executor Service

I am working on an application, where I continuously read data from a Kafka topic. This data comes in String format which I then write to an xml file & store it on hard disk. Now, this data comes randomly and mostly it's supposed to come in bulk, in quick succession.

To write these files, I am using an 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();
            }
        }

    }

I want to know when should I shutdown my executor service. If my application was time bound, I would used awaitTermination on my executor instance, but my app is supposed to run continuously.

If in case of any exception, my whole app is killed, would it automatically shutdown my executor? Or should I catch an unchecked exception and shutdown my executor, as I have done above in my code? Can I choose not to explicitly shutdown my executor in my code? What are my options?

EDIT: Since my class was a @RestController class I used the following way to shutdown my executor service

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

Upvotes: 0

Views: 653

Answers (1)

Laugslander
Laugslander

Reputation: 398

It is a good practice to shut down your ExecutorService. There are two types of shutdown that you should be aware of, 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.

Upvotes: 2

Related Questions