Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ExecutorService shutdown hook

I have console application with following threading code. It seems when i hit Ctrl+C to terminate it does not detect control keys, i have to close command prompt window.

Any clues why it is not detecting ctrl+c?

            final ExecutorService executor = Executors.newFixedThreadPool(threadPoolSize);
        final long SHUTDOWN_TIME = TimeUnit.SECONDS.toMillis(10);
        for (int i = 0; i < threadPoolSize; i++) {
            executor.submit(new MessageWorker(topicSubscriber));
        }
        //--
        //Add JVM shutdown hook
        Runtime.getRuntime().addShutdownHook(new Thread() {
            /**
             * @see java.lang.Thread#run()
             */
            @Override
            public void run() {
                executor.shutdown();
                try {
                    if (!executor.awaitTermination(SHUTDOWN_TIME, TimeUnit.SECONDS)) {
                        log.warn("Executor did not terminate in the specified time.");
                        List<Runnable> droppedTasks = executor.shutdownNow();
                        log.warn("Executor was abruptly shut down. " + droppedTasks.size() + " tasks will not be executed.");
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
like image 946
gpa Avatar asked Dec 20 '12 06:12

gpa


People also ask

How do you shut down an ExecutorService?

To properly shut down an ExecutorService, we have the shutdown() and shutdownNow() APIs. This method returns a list of tasks that are waiting to be processed. It is up to the developer to decide what to do with these tasks.

Does ExecutorService shutdown automatically?

Shutdown( ) It will not shut down The ExecutorService immediately, but it will stop accepting new tasks, and once all threads have finished their tasks, the ExecutorService will shut down.

What is JVM shutdown hook?

Shutdown hooks are called when the application terminates normally (when all threads finish, or when System. exit(0) is called).

What happens if we dont shutdown ExecutorService?

From its javadoc: "An unused ExecutorService should be shut down to allow reclamation of its resources." Calling shutdown initiates a gradual and orderly shutdown. Submitted tasks are still executed, but no new tasks will be accepted.


1 Answers

Just a guess from reading the code, but, it looks like your shutdown time is set as 10,000 seconds, so I'm not surprised you don't think it's quitting!

    final long SHUTDOWN_TIME = TimeUnit.SECONDS.toMillis(10);
    ...
    if (!executor.awaitTermination(SHUTDOWN_TIME, TimeUnit.SECONDS)) {
like image 50
SplinterReality Avatar answered Oct 12 '22 11:10

SplinterReality