Java Executor

In this tutorial, we will learn about java.util.concurrent.Executor interface, differences from executor threads to normal threads and working examples of it.

java.util.Executor interface

In Java, Executor is an interface and it is a part of the Java concurrency framework which provides a higher-level abstraction for managing threads than the java.lang.Thread class (or) it provides a standard way of executing tasks asynchronously in a multi-threaded environment.

Executor implemented class object, provides a mechanism to manage a pool of worker threads and allows to submit tasks to be executed by those pool of worker threads. The Executor interface contains a single method execute(Runnable command), which accepts a Runnable task and submits it for executing it asynchronously by one of the available worker threads from the pool.

Differences between executor threads to java.lang.Thread threads

  1. Executor threads provides higher level of abstraction, and encapsulates how threads getting created, starting, and managing. In case of normal threads creating, starting, and managing must be done. Executor threads are easier to write concurrent applications.
  2. Using an Executor is generally more efficient when it comes to resource management as compared to the normal threads. In the other hand for normal everything needs to be managed which makes complex to write concurrent applications.
  3. In normal threads, if there is any uncaught exception can lead to thread exit or application exit but in case of executor threads allows to handle exception which are uncaught during task execution.

Executor thread example:

The following example that demonstrates how to use an Executor to submit tasks for execution

CopiedCopy Code
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
public class ExecutorExample {
	public static void main(String[] args) {
		Executor executor = Executors.newSingleThreadExecutor();
		executor.execute(new Runnable() {
			@Override
			public void run() {
				System.out.println("Task executed asynchronously");
			}
		});
	}
}

Output :

Task executed asynchronously

Explanation:

In the above example, we have created an Executor reference with single task executor at a time. Submitted a runnable task to accomplish a task execution, the task ran and printed a line to the console.

Note: Please note the application will not exit until we press CTRL+C, scheduler threads will not go for shutdown requires to call shutdown method. Shutdown method is not available in Executor interface and its available from ExecutorService and this example is just for Executor interface.

Conclusion:

In this tutorial, we have covered about the executor interface, differences from executor threads to normal threads and covered a working example of the executor interface.