1

I have an application where I use Executors for creating a thread pool.

Now, I know we can create a thread pool with n number of threads in it while creating.

But in my case I don't want the pool size to be fixed. I want the application to create more threads in the pool if the users are more and automatically reduce the pool size if the users are less.

Please tell me if I'm vague and you need more information on understanding this.

Cheers!!

1
  • Maybe a ForkJoinPool? It would depend a lot on the work you're doing though, and for an application with servers I'm not really confident that that would fit...
    – awksp
    Jun 14, 2014 at 4:51

2 Answers 2

2

You probably want to use Executors.newCachedThreadPool(). Threads are created as needed, and if they go unused for a while, they will self-terminate.

2
  • Now how is this better than just creating new threads for all users?
    – mani_nz
    Jun 15, 2014 at 3:54
  • 1
    If you are asking what advantages using a thread pool brings, I believe that is addressed here and here. Creating Threads is expensive in terms of system resources, while reusing them is much cheaper.
    – VGR
    Jun 15, 2014 at 4:24
1

In general the ExecutorService has default policies that would provide out-of-the-box values for various tuning parameters for newly created threads.

Based on my understanding of your question, IMO you can control the amount of time idle threads are allowed to live within a thread-pool by using the setKeepAliveTime method.

You can refer to the documentation here for more details.

Also this link provides good resources to read about thread pools and executors available in Java

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.