Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advantage of using Executors.newSingleThreadExecutor() [duplicate]

What is the advantage of using

Executors.newSingleThreadExecutor().submit(job);

than

job.run();

where job is an instance of Runnable class.

like image 754
Abichellam Avatar asked Sep 25 '13 08:09

Abichellam


People also ask

What are the advantages of Executor framework?

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.

What is executors newSingleThreadExecutor?

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.).

Why do we use Executor service?

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.

Does newSingleThreadExecutor create a new thread?

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.


2 Answers

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.).

like image 161
Marko Topolnik Avatar answered Oct 06 '22 05:10

Marko Topolnik


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.

like image 39
Drona Avatar answered Oct 06 '22 04:10

Drona