开发者

Java - what's so great about Executors?

In a life without Java Executors, new threads would have to be created for each Runnable tasks. Making new threads requires thread overhead (creation and teardown) that adds complexity and wasted time to a non-Executor program.

Referring to code:

no Java Executor -

new Thread (aRunnableObject).start ();

with Java Executor -

Executor executor = some Executor factory method;
exector.execute开发者_运维问答 (aRunnable);

Bottom line is that Executors abstract the low-level details of how to manage threads.

Is that true?

Thanks.


Bottom line is that Executors abstract the low-level details of how to manage threads. Is that true?

Yes.

They deal with issues such as creating the thread objects, maintaining a pool of threads, controlling the number of threads are running, and graceful / less that graceful shutdown. Doing these things by hand is non-trivial.

EDIT

There may or may not be a performance hit in doing this ... compared with a custom implementation perfectly tuned to the precise needs of your application. But the chances are that:

  1. your custom implementation wouldn't be perfectly tuned, and
  2. the performance difference wouldn't be significant anyway.

Besides, the Executor support classes allow you to simply tune various parameters (e.g. thread pool sizes) if there is an issue that needs to be addressed. I don't see how garbage collection overheads would be significantly be impacted by using Executors, one way or the other.

As a general rule, you should focus on writing your applications simply and robustly (e.g. using the high level concurrency support classes), and only worry about performance if:

  1. your application is running "too slow", and
  2. the profiling tools tell you that you've got a problem in a particular area.


Couple of benefits of executors as against normal threads.

  1. Throttling can be achieved easily by varying the size of ThreadPools. This helps keeping control/check on the number of threads flowing through your application. Particularly helpful when benchmarking your application for load bearing.
  2. Better management of Runnable tasks can be achieved using the RejectionHandlers.


I think all that executors do is that they will do the low level tasks for you, but you still have to judiciously decide which thread pool do you want. I mean if your use case needs maximum 5 threads and you go and use thread pool having 100 threads, then certainly it is going to have impact on performance. Other than this there is noting extra being done at low level which is going to halt the system. And last of all, it is always better to get an idea what is being done at low level so that it will give us fair idea about the underground things.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜