Executors newSingleThreadExecutor Method Example

In this tutorial, we will learn about the Executor’s newSingleThreadExecutor factory method.

Executors.newSingleThreadExecutor() Method

This method 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 prior to the 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 newFixedThreadPool(1) the returned executor is guaranteed not to be reconfigurable to use additional threads.
Note that Executors.newSingleThreadExecutor() Method returns the newly created single-threaded Executor.
Syntax:
ExecutorService executorService = Executors.newSingleThreadExecutor();

Executors.newSingleThreadExecutor() Method Example

In this example, let's instantiates a thread pool with a single thread. All tasks are executed sequentially by the same thread.
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/*
 * Instantiates a thread pool with a single thread
 * All tasks are executed sequentially by the same thread
 */

public class SingleThreadPoolExample {

    public static void main(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.newSingleThreadExecutor();
       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
Thread main finished
Executing Task2 inside : pool-1-thread-1
Executing Task3 inside : pool-1-thread-1
We have used newSingleThreadExecutor, so when we have submitted 3 tasks, 1 new thread will be created and will execute 1 task at a time. Other 2 tasks will wait in a wait queue. As soon as one task will be completed by a thread, another task will be picked by this thread and will execute it.



Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours


Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course

Comments