amphibient
amphibient

Reputation: 31368

Using ExecutorService/ThreadPool for simple variable list of always active threads

I was debating whether there is any point in using an ExecutorService for a simple, dynamically growing list of threads of the same class, all of which are always active. I understand that Executors.newFixedThreadPool(int) provides a thread pool that can contain any number of threads but only the number specified in the method are active at any point in time. I do not have such a limitation, IOW if I add 6 threads, I want all 6 to be running concurrently.

Should I still use the Executors framework, if there are advantages to using it, or should I simply put my threads in an ArrayList?

Upvotes: 1

Views: 2543

Answers (1)

Gray
Gray

Reputation: 116938

Should I still use the Executors framework, if there are advantages to using it, or should I simply put my threads in an ArrayList?

Lot of people fork and manage their own threads. However, the main reason why the ExecutorService classes are so heavily recommended is that they take care of the management of the threads and associated tasks and reduce the amount of code that you have to write, debug, maintain. They, obviously, provide a lot of other features like Callable support, completion services, etc. which you may not use. But leaving the management to these core classes, even for simple project, is a good thing in itself. I use them even for single threaded pools because I want the Runnable task queue features of the thread-pool instead of writing my own BlockingQueue or other mechanism.

if I add 6 threads, I want all 6 to be running concurrently.

Then you should use the Executors.newCachedThreadPool(). If you submit 6 jobs (instance of Runnable or Callable) to it then 6 threads will be started to handle them. If 3 of the jobs finish and other jobs are submitted then the 3 dormant threads will run the other jobs.

NOTE: if you are submitting 1000 jobs, you will start 1000 threads which is most likely not what you want to do.


For example, to write this yourself would take a lot more code:

// a pool of 10 threads
ExecutorService threadPool = Executors.newFixedThreadPool(10);
// submit a bunch of jobs to they 10 threads for processing
for (MyJob job : jobsToDo) {
   threadPool.submit(job);
}
// no more tasks are being submitted so shutdown the pool
threadPool.shutdown();
// wait for the jobs to finish
threadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);

Upvotes: 2

Related Questions