Skip to content

Executors Utility Class in Java

Ramesh Fadatare edited this page Sep 10, 2018 · 3 revisions

Executors Class provides factory and utility methods for Executor, ExecutorService, ScheduledExecutorService, ThreadFactory, and Callable classes defined in this package.

This class supports the following kinds of methods:

  • Methods that create and return an ExecutorService set up with commonly useful configuration settings.
  • Methods that create and return a ScheduledExecutorService set up with commonly useful configuration settings.
  • Methods that create and return a "wrapped" ExecutorService, that disables reconfiguration by making implementation-specific methods inaccessible.
  • Methods that create and return a ThreadFactory that sets newly created threads to a known state.
  • Methods that create and return a Callable out of other closure-like forms, so they can be used in execution methods requiring Callable.

Executors Utility class provides a list factory and utility methods are shown in below class diagram.

diagram here

In this article, we will discuss five important utility methods of Executors class with example.

  1. Executors.newFixedThreadPool(int nThreads) Method
  2. Executors.newSingleThreadExecutor() Method
  3. Executors.newCachedThreadPool() Method
  4. Executors.newScheduledThreadPool Method
  5. Executors.newSingleThreadScheduledExecutor() Method

Executors.newCachedThreadPool() Method

This method creates a thread pool that creates new threads as needed but will reuse previously constructed threads when they are available. These pools will typically improve the performance of programs that execute many short-lived asynchronous tasks.

Calls to execute will reuse previously constructed threads if available. If no existing thread is available, a new thread will be created and added to the pool. Threads that have not been used for sixty seconds are terminated and removed from the cache. Thus, a pool that remains idle for long enough will not consume any resources. Note that pools with similar properties but different details (for example, timeout parameters) may be created using ThreadPoolExecutor constructors.

Syntax:

final ExecutorService executorService = Executors.newCachedThreadPool();

Executors.newCachedThreadPool() Method Example

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class CachedThreadPoolExample {

    public static void main(final String[] args) throws InterruptedException, ExecutionException {

        System.out.println("Thread main started");

        Runnable task1 = () -> {
             System.out.println("Executing Task1 inside : " + Thread.currentThread().getName());
             try {
                  TimeUnit.SECONDS.sleep(2);
             } catch (InterruptedException ex) {
                  throw new IllegalStateException(ex);
             }
        };

        Runnable task2 = () -> {
             System.out.println("Executing Task2 inside : " + Thread.currentThread().getName());
             try {
                  TimeUnit.SECONDS.sleep(4);
             } catch (InterruptedException ex) {
                  throw new IllegalStateException(ex);
             }
       };

        Runnable task3 = () -> {
            System.out.println("Executing Task3 inside : " + Thread.currentThread().getName());
            try {
                 TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException ex) {
                 throw new IllegalStateException(ex);
            }
        };

        final ExecutorService executorService = Executors.newCachedThreadPool();
        System.out.println("Submitting the tasks for execution...");
        executorService.submit(task1);
        executorService.submit(task2);
        executorService.submit(task3);

        executorService.shutdown();

        System.out.println("Thread main finished");
    }
}

Output:

Thread main started
Submitting the tasks for execution...
Executing Task1 inside : pool-1-thread-1
Executing Task3 inside : pool-1-thread-3
Executing Task2 inside : pool-1-thread-2
Thread main finished

Executors.newSingleThreadScheduledExecutor() Method

Creates a single-threaded executor that can schedule commands to run after a given delay, or to execute periodically. (Note however that if this single thread terminates due to a failure during execution prior to shutdown, a new one will take its place if needed to execute subsequent tasks.) Tasks are guaranteed to execute sequentially, and no more than one task will be active at any given time. Unlike the otherwise equivalent newScheduledThreadPool(1) the returned executor is guaranteed not to be reconfigurable to use additional threads.

Syntax:

ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();

Executors.newSingleThreadScheduledExecutor() Method Example

import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ExecutorsDemo {

	public static void main(String[] args) {
		ExecutorsDemo demo = new ExecutorsDemo();
		demo.newSingleThreadScheduledExecutor();
	}

	private void newSingleThreadScheduledExecutor() {
		System.out.println("Thread main started");

		ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();

		// Create a task
		Runnable task1 = () -> {
			System.out.println("Executing the task1 at: " + new Date());
		};

		scheduledExecutorService.scheduleAtFixedRate(task1, 0, 2, TimeUnit.SECONDS);

		System.out.println("Thread main finished");
	}

}

Output:

Thread main started
Thread main finished
Executing the task1 at: Mon Sep 10 13:15:57 IST 2018
Executing the task1 at: Mon Sep 10 13:15:59 IST 2018
Executing the task1 at: Mon Sep 10 13:16:01 IST 2018
Executing the task1 at: Mon Sep 10 13:16:03 IST 2018
Executing the task1 at: Mon Sep 10 13:16:05 IST 2018
Executing the task1 at: Mon Sep 10 13:16:07 IST 2018
...............