🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
The Executors class in Java provides the newSingleThreadScheduledExecutor() method to create a single-threaded executor that can schedule commands to run after a given delay or to execute periodically.
This guide will cover the usage of the newSingleThreadScheduledExecutor() method, explain how it works, and provide concise examples to demonstrate its functionality in real-world use cases.
Introduction
The Executors.newSingleThreadScheduledExecutor() method creates a single-threaded executor 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, while ensuring that tasks are executed sequentially by a single thread.
newSingleThreadScheduledExecutor Method Syntax
The syntax for the newSingleThreadScheduledExecutor method is as follows:
public static ScheduledExecutorService newSingleThreadScheduledExecutor()
- The method does not take any parameters.
- The method returns a
ScheduledExecutorServicethat can be used to schedule commands.
Examples
Example 1: Scheduling a Task with a Fixed Delay
In this example, we create a single-threaded scheduled executor 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 SingleThreadScheduledExecutorExample {
public static void main(String[] args) {
// Create a single-thread scheduled executor
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
// 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 single-threaded scheduled executor 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 single-thread scheduled executor
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
// 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 single-threaded scheduled executor 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 single-thread scheduled executor
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
// 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 single-threaded scheduled executor 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 single-thread scheduled executor
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
// 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-1
Periodic task executed by pool-1-thread-1
Periodic task executed by pool-1-thread-1
Another periodic task executed by pool-1-thread-1
Periodic task executed by pool-1-thread-1
Periodic task executed by pool-1-thread-1
Another periodic task executed by pool-1-thread-1
Executor shutdown
Conclusion
The Executors.newSingleThreadScheduledExecutor() method in Java is used for creating a single-threaded executor that supports task scheduling. It can schedule commands to run after a given delay or to execute periodically, ensuring that tasks are executed sequentially by a single thread.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment