Some questions about Executors best usage for memory and time performance:
-
Is there any cost penalty incurred for the use of
ExecutorService e = Executors.newSingleThreadExecutor(); e.execute(callable) e.shutdown()compared to:
new Thread(runnable).start() -
If a
Callableis not a long one, and never won’t be more than one instance running of it it’s ok to use the code from (1)? Or is it best to haveExecutorServiceas a static instance and reuse between calls? -
If I have several tasks as described in (2) is there any problem with every task to having its own executor service or is better to have a centralized one? (I’m talking about a client application where normally there won’t be more than one of these tasks running)
-
What resources does an
Executorconsume if it isn’t shutdown()?
Yes, there is a “penalty”: the
ExecutorServicewill most likely be more expensive to create since it also creates a queue for the tasks you’re submitting and if a thread fails prior to shutdown, then the failed thread will be replaced with another one in order to run any subsequent tasks (so there is quite a bit of logic there). However, you probably don’t want to be creating anExecutiveServiceeach time you want to run a task… that’s probably not the best use of anExecutorService(more on that in the next question).The suggested use of the
ExecutorServiceis as a thread pool, where you keep theExecutorServicearound and you keep submitting tasks to it as long as you have tasks to submit. It can be static or just a regular member, that is irrelevant and highly dependent on your requirements/design. Even if you’re only running one instance at a time (i.e. you only have a single-threaded executor), it’s still more efficient to use theExecutorServicebecause it reuses the thread, so in the long run it will be less expensive than creating a new thread for each task you submit.There is no problem, but it’s inefficient, so just have a centralized executor service.
I don’t think you should worry about that in particular, especially if you’re using the
Executorin the correct context it will be minimal.