What is the advantage of using
Executors.newSingleThreadExecutor().submit(job);
than
job.run();
where job
is an instance of Runnable
class.
Below are some benefits: Executor service manage thread in asynchronous way. Use Future callable to get the return result after thread completion. Manage allocation of work to free thread and resale completed work from thread for assigning new work automatically.
The newSingleThreadExecutor() method of Executors class creates an Executor that uses a single worker thread operating off an unbounded queue. (Note however that if this single thread terminates due to a failure during execution before the shutdown, a new one will take its place if needed to execute subsequent tasks.).
The ExecutorService helps in maintaining a pool of threads and assigns them tasks. It also provides the facility to queue up tasks until there is a free thread available if the number of tasks is more than the threads available.
newSingleThreadExecutor. Creates an Executor that uses a single worker thread operating off an unbounded queue, and uses the provided ThreadFactory to create a new thread when needed.
Writing literally
Executors.newSingleThreadExecutor().submit(job);
is pointless: it's just the wrong way to do
new Thread(job).start();
As opposed to the latter, the former will leave the thread hanging on until the Executor Service is finalized.
The advantage of using an Executor Service comes about when you keep it around as an instance/class variable and reuse it for many submitted tasks. The Executor Service must be properly shutdown
when you are done with it.
More generally, the difference between submitting tasks to an executor service and just running the tasks is in the achieved concurrency. Whether that results in any advantage is highly specific to the job being submitted: it may also be useless or even broken (causing data races, deadlocks, etc.).
The difference is same as in new Thread(job).start()
and job.run()
. When you submit the job for execution, the job runs in one of the available thread of the executor. Calling job.run()
is simply like any other method call which does not run in a separate thread but rather on the calling thread.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With