tags:

views:

167

answers:

2

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.

+6  A: 

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.
Stephen C
Executors are easier to use since they handle low-level thread management. Is there any performance hit?I'm thinking in my head -garbage collection :: manual mem mgmt : executor :: thread
BIll
`Executor` is an interface, so your perfectly tuned custom implementation can in fact be an `Executor`. Then, if it turns out not to be so perfectly tuned, you can switch implementations easily. :)
Matthew Flaschen
thanks! you da man
BIll
Abstraction provided by Executors are very light weight, in the sense they don't do that much. In case of fixedThreadPool, there is a queue and some waiting threads. If work comes in, they'll do the work. But that's basically all, so that is highly unlikely to give you any performance hit.
Enno Shioji
+1  A: 

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.
Tushar Tarkas