Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of a Thread pool in Java?

What is the use of a Thread pool? Is there a good real world example?

like image 524
JavaUser Avatar asked Jul 20 '10 02:07

JavaUser


People also ask

What is the use of thread pool?

The thread pool is primarily used to reduce the number of application threads and provide management of the worker threads. Applications can queue work items, associate work with waitable handles, automatically queue based on a timer, and bind with I/O.

What happens when thread pool is full?

By default, the MaxThreads of the ThreadPool is very high. Usually you'll never get there, your app will crash first. So when all threads are busy the new tasks are queued and slowly, at most 1 per 500 ms, the TP will allocate new threads.

What is the use of thread pool and how we can write our own in Java?

In Java, thread pool is implemented in ThreadPoolExecutor class. There are four core concepts in ThreadPoolExecutor. A work queue is used as a “buffer” to hold submitted tasks in a thread pool. When the size of a work queue reaches its capacity, we cannot submit new tasks to a thread pool anymore.

What is thread polling in Java?

The process of testing a condition repeatedly till it becomes true is known as polling. Polling is usually implemented with the help of loops to check whether a particular condition is true or not. If it is true, a certain action is taken. This wastes many CPU cycles and makes the implementation inefficient.


2 Answers

A thread pool is a group of threads initially created that waits for jobs and executes them. The idea is to have the threads always existing, so that we won't have to pay overhead time for creating them every time. They are appropriate when we know there's a stream of jobs to process, even though there could be some time when there are no jobs.

Here's a nice diagram from Wikipedia: alt text

like image 175
Amir Rachum Avatar answered Oct 02 '22 01:10

Amir Rachum


Thread Pools from the Java Tutorials has a good overview:

Using worker threads minimizes the overhead due to thread creation. Thread objects use a significant amount of memory, and in a large-scale application, allocating and deallocating many thread objects creates a significant memory management overhead.

like image 25
Justin Ethier Avatar answered Oct 02 '22 01:10

Justin Ethier