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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With