d-man
d-man

Reputation: 58083

Java Webapp Executors class

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);

Upvotes: 0

Views: 134

Answers (1)

Edwin Buck
Edwin Buck

Reputation: 70909

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 threadRunner pool, as it will bind to one of the completed task's former threads(activeQueueRunner or standbyQueueRunner), and use that thread to exercise its run(...) 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 Executor type 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.

Upvotes: 2

Related Questions