Java Executor and Long-lived Threads

怎甘沉沦 提交于 2019-12-12 20:00:30

问题


I've inherited some code that uses Executors.newFixedThreadPool(4); to run the 4 long-lived threads that do all the work of the application.

Is this recommended? I've read the Java Concurrency in Practice book and there does not seem to be much guidance around how to manage long-lived application threads.

What is the recommended way to start and manage several threads that each live for the entire live of the application?


回答1:


You mentioned that code is using Executors, it should be returning an ExecutorService

ExecutorService executor = Executors.newFixedThreadPool(NTHREDS);

ExecutorService is an Executor that provides methods to manage termination and methods that can produce a Future for tracking progress of one or more asynchronous tasks.

As long as returned ExecutorService is performing graceful shutdown there should not be an issue.

You can check that your code is doing shutodwn by finding following in your code:

// This will make the executor accept no new threads
// and finish all existing threads in the queue
executor.shutdown();

// Wait until all threads are finish
executor.awaitTermination();

Cheers !!




回答2:


I assume that your long-lived thread do some periodic job in a loop. What you can do is the following:

  1. Make sur that each runnable in the pool checks the pool's state before looping.

    while( ! pool.isShutdown() ) { ... }

    Your runnable must thus have a reference to their parent pool.

  2. Install a JVM shutdown hook with Runtime.addShutdownHook(). The hook calls pool.shutdown() then pool.awaitTermination(). The pool will transition to the SHUTDOWN state and eventually the threads will stop, after which it will transition to the TERMINATED state.

--

That said, I'm a bit suspicious of your 4 threads. Shouldn't there be only 1 long-live threads, which fetches tasks, and submits them to an executor service? Do you really have 4 different long-lived processes? (This consideration is orthogonal to the main question).



来源:https://stackoverflow.com/questions/19366661/java-executor-and-long-lived-threads

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!