Executors newSingleThreadExecutor Method Example

Introduction

The newSingleThreadExecutor method in the Executors class creates an ExecutorService that uses a single worker thread operating off an unbounded queue. This type of executor is useful when you want to ensure that tasks are executed sequentially and in the order they are submitted.

Table of Contents

  1. Overview of newSingleThreadExecutor Method
  2. Creating a Single-Thread Executor
  3. Submitting Tasks to Single-Thread Executor
  4. Example: Using newSingleThreadExecutor
  5. Shutting Down the Executor
  6. Conclusion

1. Overview of newSingleThreadExecutor Method

The newSingleThreadExecutor method creates an ExecutorService with a single worker thread. This thread executes tasks sequentially and ensures that no more than one task is active at any given time.

Syntax:

public static ExecutorService newSingleThreadExecutor()

2. Creating a Single-Thread Executor

To create a single-thread executor, use the newSingleThreadExecutor method.

Example:

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

public class SingleThreadExecutorExample {
    public static void main(String[] args) {
        // Creating a single-thread executor
        ExecutorService executorService = Executors.newSingleThreadExecutor();

        // Your tasks go here

        executorService.shutdown();
    }
}

3. Submitting Tasks to Single-Thread Executor

Tasks can be submitted to the single-thread executor using the submit or execute method.

Example:

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

public class SingleThreadExecutorTaskExample {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newSingleThreadExecutor();

        // Submit tasks to the executor service
        for (int i = 1; i <= 5; i++) {
            final int taskId = i;
            executorService.submit(() -> {
                System.out.println("Task " + taskId + " executed by " + Thread.currentThread().getName());
                try {
                    Thread.sleep(1000); // Simulate a long-running task
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }

        executorService.shutdown();
    }
}

Output:

Task 1 executed by pool-1-thread-1
Task 2 executed by pool-1-thread-1
Task 3 executed by pool-1-thread-1
Task 4 executed by pool-1-thread-1
Task 5 executed by pool-1-thread-1

4. Example: Using newSingleThreadExecutor

Let's create a complete example that demonstrates how to create a single-thread executor, submit tasks, and shut it down.

Example:

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

class Task implements Runnable {
    private final String name;

    public Task(String name) {
        this.name = name;
    }

    @Override
    public void run() {
        System.out.println("Task " + name + " is being executed by " + Thread.currentThread().getName());
        try {
            Thread.sleep(1000); // Simulate long-running task
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

public class SingleThreadExecutorDemo {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newSingleThreadExecutor();

        for (int i = 1; i <= 5; i++) {
            Task task = new Task("Task " + i);
            executorService.submit(task);
        }

        executorService.shutdown();

        try {
            if (!executorService.awaitTermination(60, TimeUnit.SECONDS)) {
                executorService.shutdownNow();
            }
        } catch (InterruptedException e) {
            executorService.shutdownNow();
        }

        System.out.println("All tasks are finished.");
    }
}

Output:

Task Task 1 is being executed by pool-1-thread-1
Task Task 2 is being executed by pool-1-thread-1
Task Task 3 is being executed by pool-1-thread-1
Task Task 4 is being executed by pool-1-thread-1
Task Task 5 is being executed by pool-1-thread-1
All tasks are finished.

Explanation:

  • The Task class implements the Runnable interface and represents a task that prints its name and the name of the thread executing it.
  • The SingleThreadExecutorDemo class creates a single-thread executor using the newSingleThreadExecutor method.
  • Five tasks are submitted to the executor service.
  • Each task prints its name and the name of the thread executing it.
  • The executor service is shut down gracefully, waiting for up to 60 seconds for tasks to complete.

5. Shutting Down the Executor

It's important to properly shut down the ExecutorService to release resources. You can shut it down gracefully or forcefully.

Graceful Shutdown:

executorService.shutdown();
try {
    if (!executorService.awaitTermination(60, TimeUnit.SECONDS)) {
        executorService.shutdownNow();
    }
} catch (InterruptedException e) {
    executorService.shutdownNow();
}

Forceful Shutdown:

executorService.shutdownNow();

6. Conclusion

The newSingleThreadExecutor method in the Executors class provides a convenient way to create an ExecutorService that uses a single worker thread. This type of executor is useful for tasks that need to be executed sequentially and in the order they are submitted. By using newSingleThreadExecutor, you can efficiently manage and execute tasks in your applications.

Happy coding!

Comments