Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - what's so great about Executors?

Tags:

java

executor

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.

like image 925
BIll Avatar asked Aug 16 '26 07:08

BIll


2 Answers

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.
like image 109
Stephen C Avatar answered Aug 18 '26 19:08

Stephen C


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.
like image 39
Tushar Tarkas Avatar answered Aug 18 '26 20:08

Tushar Tarkas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!