In the execution service there are many ways to do a trick I have been googling around and found a lot of words but none of them explains well what is what and why.
Solvation:
Most of the executor service are obtained through the Executors class like:
Executors.newCachedThreadPool();
This threadpool provides you with the number of threads that you need. It reuses threads that come available again.
Executors.newFixedThreadPool(10);
This threadpool only provides you with the number of threads that you have declared 10 in my example.
Executors.newSingleThreadExecutor();
This threadpool contains one single thread and all given tasks will be executed in sequence.
Except ofr the SingleThreadExecutor() all of the others deal the same way if it becomes to lists. As soon you expose a list to one of the named threadpools the behaviour is as follows:
Lets say we take a CachedThreadPool or a FixedThreadPool we expose a list of elements to the executorservice initialized with one of the above named pools. The first element of that is exposed for threading it will be spread over all the available threads. As soon the task is done, the next element of the list will use all of the threads. This is a good thing if that is what you desire. But what if you want to share all the elements of the list shared over different threads. In other words every element of the list should be worked on at the same moment in parallel.
This is where the only pool comes in that can do that is the ForkJoinPool (since java 7). This pool is not obtained through the Executors class but is instanciated on its own like :
ForkJoinPool forkJoinPool = new ForkJoinPool(3); The constructor takes a int as argument to initialize the number of threads, 3 in my example. The ForkJoinPool uses the work-stealing philosophy. This means that if a thread is running out of jobs, it will visit one of the neighbor threads and see if he can help him out.
Conclusion:
If you want to work a single task in different threads the ExecutionService is what you need. If you need different tasks work in paralel the same time, you should use the ForkJoinPool.
If you are using a version of Java lesser then 7, you can try this trick with google guava. I worked at this time with version 18.0 and that worked fine. Here is a piece of example code:
//Java class
ExecutorService executorService = Executors.newCachedThreadPool();
//Guava class
ExecutionList executionList = new ExecutionList();
//code to execute
executionList.add( new myRunnable(), executorService);executionList.execute();
Have fun!