Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Keep-alive work with ThreadPoolExecutor?

In continuation to a question posted by me, I'm trying to use ThreadPoolExecutor in my codebase. Even after repeated attempts to comprehend from Java API doc, I failed to understand clearly the functionality/purpose behind keepAliveTime parameter to be passed in the constructor. Hope somebody can explain me with some good working example.

Excerpts from Java doc:

public ThreadPoolExecutor(int corePoolSize,                           int maximumPoolSize,                           long keepAliveTime,                           TimeUnit unit,                           BlockingQueue<Runnable> workQueue) 

keepAliveTime - when the number of threads is greater than the core, this is the maximum time that excess idle threads will wait for new tasks before terminating.

like image 463
Gnanam Avatar asked Apr 30 '12 06:04

Gnanam


People also ask

What is keep alive time in ThreadPoolExecutor?

Returns the thread keep-alive time, which is the amount of time which threads in excess of the core pool size may remain idle before being terminated.

How does ThreadPoolExecutor work in Java?

ThreadPoolExecutor is an ExecutorService to execute each submitted task using one of possibly several pooled threads, normally configured using Executors factory methods. It also provides various utility methods to check current threads statistics and control them.

How does ThreadPoolExecutor work in Python?

ThreadPoolExecutor. ThreadPoolExecutor is an Executor subclass that uses a pool of threads to execute calls asynchronously. An Executor subclass that uses a pool of at most max_workers threads to execute calls asynchronously.

How do you prevent ThreadPoolExecutor?

Call cancel() on the Future to Cancel a Task You can cancel tasks submitted to the ThreadPoolExecutor by calling the cancel() function on the Future object. Recall that you will receive a Future object when you submit your task to the thread pool by calling the submit() function.


1 Answers

Suppose you have a core size of 5, and a maximum size of 15. For some reason your pool gets busy, and uses all 15 available threads. Eventually you run out of work to do - so some of your threads become idle as they finish their final task. So 10 of those threads are allowed to die.

However, to avoid them being killed off too quickly, you can specify the keep-alive time. So if you specified 1 as the keepAliveTime value and TimeUnit.MINUTE as the unit value, each thread would wait one minute after it had finished executing a task to see if there was more work to do. If it still hadn't been given any more work, it would let itself complete, until there were only 5 threads in the pool - the "core" of the pool.

like image 95
Jon Skeet Avatar answered Sep 29 '22 07:09

Jon Skeet