Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advantages of Executors over new Thread

What benefit is there to use Executors over just Threads in a Java program.

Such as

ExecutorService pool = Executors.newFixedThreadPool(2);
void someMethod() {
    //Thread
    new Thread(new SomeRunnable()).start();

    //vs

    //Executor
    pool.execute(new SomeRunnable());
}

Does an executor just limit the number of threads it allows to have running at once (Thread Pooling)? Does it actually multiplex runnables onto the threads it creates instead? If not is it just a way to avoid having to write new Thread(runnable).start() every time?

like image 289
Chase Avatar asked Aug 28 '13 19:08

Chase


People also ask

Why the Executor framework is better than creating and managing thread by the application?

Why use it? The Executor Framework contains a bunch of components that are used to efficiently manage multiple threads. It was released with the JDK 5 which is used to run the Runnable objects without creating new threads every time and also mostly re-using the already created threads.

What is the difference between thread and Executor?

A Thread represents something which is responsible for executing your code in parallel, while an Executor is an abstraction for concurrent task execution.

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.

Which happens when more tasks are submitted to a thread Executor than available threads?

Tasks are submitted to a thread pool via an internal queue called the Blocking Queue. If there are more tasks than the number of active threads, they are inserted into the blocking queue for waiting until any thread becomes available.


1 Answers

Yes, executors will generally multiplex runnables onto the threads they create; they'll constrain and manage the number of threads running at once; they'll make it much easier to customize concurrency levels. Generally, executors should be preferred over just creating bare threads.

like image 165
Louis Wasserman Avatar answered Sep 28 '22 07:09

Louis Wasserman