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!!

mani_nz
  • 4,522
  • 3
  • 28
  • 37
  • *Maybe* a [`ForkJoinPool`](http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ForkJoinPool.html)? 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 '14 at 04:51

2 Answers2

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.

VGR
  • 40,506
  • 4
  • 48
  • 63
  • Now how is this better than just creating new threads for all users? – mani_nz Jun 15 '14 at 03:54
  • 1
    If you are asking what advantages using a thread pool brings, I believe that is addressed [here](http://stackoverflow.com/questions/3286626/what-is-the-use-of-a-thread-pool-in-java) and [here](http://docs.oracle.com/javase/tutorial/essential/concurrency/pools.html). Creating Threads is expensive in terms of system resources, while reusing them is much cheaper. – VGR Jun 15 '14 at 04: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

Prahalad Deshpande
  • 4,709
  • 1
  • 20
  • 22