Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should we use Java's Thread over Executor?

People also ask

What are the advantages given by the executors framework over the thread API?

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

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.

What is the use of thread pool Executor in Java?

ThreadPoolExecutor is an ExecutorService to execute each submitted task using one of possibly several pooled threads, normally configured using Executors factory methods. It also provides various utility methods to check current threads statistics and control them.


To give some history, Executors were only added as part of the java standard in Java 1.5. So in some ways Executors can be seen as a new better abstraction for dealing with Runnable tasks.

A bit of an over-simplification coming... - Executors are threads done right so use them in preference.


I use Thread when I need some pull based message processing. E.g. a Queue is take()-en in a loop in a separate thread. For example, you wrap a queue in an expensive context - lets say a JDBC connection, JMS connection, files to process from single disk, etc.

Before I get cursed, do you have some scenario?

Edit:

As stated by others, the Executor (ExecutorService) interface has more potential, as you can use the Executors to select a behavior: scheduled, prioritized, cached etc. in Java 5+ or a j.u.c backport for Java 1.4.

The executor framework has protection against crashed runnables and automatically re-create worker threads. One drawback in my opinion, that you have to explicitly shutdown() and awaitTermination() them before you exit your application - which is not so easy in GUI apps. If you use bounded queues you need to specify a RejectedExecutionHandler or the new runnables get thrown away.

You might have a look at Brian Goetz et al: Java Concurrency in Practice (2006)


There is no advantage to using raw threads. You can always supply Executors with a Thread factory, so even the option of custom thread creation is covered.


You don't use Thread unless you need more specific behaviour that is not found in Thread itself. You then extend Thread and add your specifically wanted behaviour.

Else just use Runnable or Executor.


Well, I thought that a ThreadPoolExecutor provided better performance for it manages a pool of threads, minimizing the overhead of instantiating a new thread, allocating memory...

And if you are going to launch thousands of threads, it gives you some queuing functionality you would have to program by yourself...

Threads & Executors are different tools, used on different scenarios... As I see it, is like asking why should I use ArrayList when I can use HashMap? They are different...


java.util.concurrent package provides executor interface and can be used to created thread.

The Executor interface provides a single method, execute, designed to be a drop-in replacement for a common thread-creation idiom. If r is a Runnable object, and e is an Executor object you can replace

(new Thread(r)).start();

with

e.execute(r);

Refer here


It's always better to prefer Executor to Thread even for single thread as below

ExecutorService fixedThreadPool = Executors.newFixedThreadPool(1);

You can use Thread over Executor in below scenarios

  1. Your application needs limited thread(s) and business logic is simple

  2. If simple multi-threading model caters your requirement without Thread Pool

  3. You are confident of managing thread(s) life cycle + exception handling scenarios with help of low level APIs in below areas : Inter thread communication, Exception handling, reincarnation of threads due to unexpected errors

and one last point

  1. If your application does not need customization of various features of ThreadPoolExecutor

    ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, 
    TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, 
    RejectedExecutionHandler handler)
    

In all other cases, you can go for ThreadPoolExecutor