Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How expensive is creating of a new thread in Java? When should we consider using of a thread pool?

I wonder where is the verge after which a thread pool should be used. How many new threads per second can I create without using a thread pool still avoiding noticeable performance penalty?

Are there any observable open-source thread-pool implementations?

like image 651
Roman Avatar asked Jul 07 '10 13:07

Roman


People also ask

Should you use a thread pool or just create a new thread whenever you need it?

I would advise you to use a ThreadPool instead of creating a new Thread. You can have a beginning of answer in Oracle's documentation about thread pools.

Is it expensive to create threads?

Thread creation is very expensive relative to the creation of most objects, but not very expensive relative to a random harddisk seek. You don't have to avoid creating threads at all costs, but creating hundreds of them per second is not a smart move.

What is thread pool How can we create thread pool in Java?

A thread pool reuses previously created threads to execute current tasks and offers a solution to the problem of thread cycle overhead and resource thrashing. Since the thread is already existing when the request arrives, the delay introduced by thread creation is eliminated, making the application more responsive.

Why do we need thread pool in Java?

A thread pool helps mitigate the issue of performance by reducing the number of threads needed and managing their lifecycle. Essentially, threads are kept in the thread pool until they're needed, after which they execute the task and return the pool to be reused later.


1 Answers

Considering the cost, the only valid reply is to test it for yourself (not-so-elegant way to tell you I have never done such a test, and will never do it, as modern Execution mechanism provides far advanced creation/destruction mechanisms).

Consdering existing implementations, Java modern versions (starting with Java 5) offers various subclasses of ThreadPoolExecutor that combines the benefits of a thread pool with the most modern concepts of java.util.concurrent : Executors.

Besides, I would never recommand enough to you to forget about Threads and to repalce them with Runnable, callable and other more advanced computation objects. This way, you can easily switch implementation of Executors.

like image 177
Riduidel Avatar answered Oct 20 '22 00:10

Riduidel