Java Executors newScheduledThreadPool() Method

The Executors class in Java provides the newScheduledThreadPool() method to create a thread pool that can schedule commands to run after a given delay or to execute periodically. This guide will cover the usage of the newScheduledThreadPool() method, explain how it works, and provide concise examples to demonstrate its functionality in real-world use cases.

Introduction

The Executors.newScheduledThreadPool() method creates a thread pool that supports scheduling of tasks. This can be useful for tasks that need to be executed at a fixed rate or after a specific delay.

newScheduledThreadPool Method Syntax

The syntax for the newScheduledThreadPool method is as follows:

public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize)
  • The method takes a single parameter corePoolSize, which specifies the number of threads in the pool.
  • The method returns a ScheduledExecutorService that can be used to schedule commands.

Examples

Example 1: Scheduling a Task with a Fixed Delay

In this example, we create a scheduled thread pool and schedule a task to run after a fixed delay.

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

public class FixedDelayExample {
    public static void main(String[] args) {
        // Create a scheduled thread pool with 2 threads
        ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);

        // Schedule a task to run after a 5-second delay
        executor.schedule(() -> {
            System.out.println("Task executed after 5-second delay");
        }, 5, TimeUnit.SECONDS);

        // Shutdown the executor after the task is executed
        executor.schedule(() -> {
            executor.shutdown();
            System.out.println("Executor shutdown");
        }, 6, TimeUnit.SECONDS);
    }
}

Output:

Task executed after 5-second delay
Executor shutdown

Example 2: Scheduling a Task at a Fixed Rate

In this example, we use a scheduled thread pool to schedule a task to run at a fixed rate.

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

public class FixedRateExample {
    public static void main(String[] args) {
        // Create a scheduled thread pool with 2 threads
        ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);

        // Schedule a task to run at a fixed rate of 2 seconds
        executor.scheduleAtFixedRate(() -> {
            System.out.println("Task executed at fixed rate by " + Thread.currentThread().getName());
        }, 0, 2, TimeUnit.SECONDS);

        // Schedule executor shutdown after 10 seconds
        executor.schedule(() -> {
            executor.shutdown();
            System.out.println("Executor shutdown");
        }, 10, TimeUnit.SECONDS);
    }
}

Output:

Task executed at fixed rate by pool-1-thread-1
Task executed at fixed rate by pool-1-thread-1
Task executed at fixed rate by pool-1-thread-1
Task executed at fixed rate by pool-1-thread-1
Task executed at fixed rate by pool-1-thread-1
Executor shutdown

Example 3: Scheduling a Task with a Fixed Delay Between Executions

In this example, we use a scheduled thread pool to schedule a task with a fixed delay between the end of the last execution and the start of the next.

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

public class FixedDelayBetweenExecutionsExample {
    public static void main(String[] args) {
        // Create a scheduled thread pool with 2 threads
        ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);

        // Schedule a task with a fixed delay of 3 seconds between the end of the last execution and the start of the next
        executor.scheduleWithFixedDelay(() -> {
            System.out.println("Task executed with fixed delay by " + Thread.currentThread().getName());
        }, 0, 3, TimeUnit.SECONDS);

        // Schedule executor shutdown after 12 seconds
        executor.schedule(() -> {
            executor.shutdown();
            System.out.println("Executor shutdown");
        }, 12, TimeUnit.SECONDS);
    }
}

Output:

Task executed with fixed delay by pool-1-thread-1
Task executed with fixed delay by pool-1-thread-1
Task executed with fixed delay by pool-1-thread-1
Executor shutdown

Example 4: Periodic Task Execution

In this example, we use a scheduled thread pool to schedule a periodic task.

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

public class PeriodicTaskExample {
    public static void main(String[] args) {
        // Create a scheduled thread pool with 3 threads
        ScheduledExecutorService executor = Executors.newScheduledThreadPool(3);

        // Schedule a task to run every 1 second
        executor.scheduleAtFixedRate(() -> {
            System.out.println("Periodic task executed by " + Thread.currentThread().getName());
        }, 0, 1, TimeUnit.SECONDS);

        // Schedule another task to run every 2 seconds
        executor.scheduleAtFixedRate(() -> {
            System.out.println("Another periodic task executed by " + Thread.currentThread().getName());
        }, 0, 2, TimeUnit.SECONDS);

        // Schedule executor shutdown after 7 seconds
        executor.schedule(() -> {
            executor.shutdown();
            System.out.println("Executor shutdown");
        }, 7, TimeUnit.SECONDS);
    }
}

Output:

Periodic task executed by pool-1-thread-1
Another periodic task executed by pool-1-thread-2
Periodic task executed by pool-1-thread-1
Periodic task executed by pool-1-thread-1
Another periodic task executed by pool-1-thread-2
Periodic task executed by pool-1-thread-1
Periodic task executed by pool-1-thread-1
Periodic task executed by pool-1-thread-3
Another periodic task executed by pool-1-thread-2
Executor shutdown

Conclusion

The Executors.newScheduledThreadPool() method in Java is used for creating a thread pool that supports task scheduling. It can schedule commands to run after a given delay or to execute periodically, making it suitable for applications that require timed or repeated task execution. 

Comments