Java – webapp what is the advantage of executing thread via Executors class as following code other then running with fixed pool size.
private ExecutorService threadRunner;
threadRunner = Executors.newFixedThreadPool(2);
threadRunner.submit(activeQueueRunner);
threadRunner.submit(standbyQueueRunner);
Threads contain a lot of supporting structures which are expensive to create. Executors are pools of threads that get created once, but are wrapped with the required supporting code to be reused amongst multiple tasks.
In other words, if you are submitting only two items to a new fixed thread pool of size two, you have no advantage. The advantage comes when you submit your third item to the
threadRunnerpool, as it will bind to one of the completed task’s former threads(activeQueueRunnerorstandbyQueueRunner), and use that thread to exercise itsrun(...)block.If you write your submitted tasks to never complete, then they will basically never release the thread back to the pool. So when using an
Executortype pool, it is a good idea to make lots of quick lightweight tasks and let the pool amortize the expensive cost of creating / destroying Threads over the entire run of the program.