#
Executor Service : ScheduledThreadPool
This tutorial explains how to use the Executor Service in Java.
The Java ExecutorService is the interface which allows us to execute tasks on threads asynchronously. It defines a pool of threads to be used.
How you create an ExecutorService depends on the implementation you use.
Examples:
// It create a single thread pool
ExecutorService es1 = Executors.newSingleThreadExecutor();
// It create a thread pool with maximum 10 threads
ExecutorService es2 = Executors.newFixedThreadPool(10);
// It create a thread pool with maximum 10 threads. The tasks could be scheduled using a pattern.
ScheduledExecutorService es3 = Executors.newScheduledThreadPool(10);
ScheduledExecutorService could be used for:
- Run a task one time after a number of seconds (you can receive or not a value of the end of the task, function of the implementation)
- Repeating the task every n second, with an initial delay
Take a look at the following example and read carefully the comment in the code.
package com.exampe.java;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) throws InterruptedException, ExecutionException {
SpringApplication.run(DemoApplication.class, args);
System.out.println("--------------------------------------------");
Runnable task1 = () -> {
System.out.println("Task #1 is running");
};
Callable<Integer> task2 = () -> {
{
System.out.println("Task #2 is running");
};
return 2;
};
Runnable task3 = () -> {
{
System.out.println("Task #3 is running");
};
};
ScheduledExecutorService es1 = Executors.newScheduledThreadPool(10);
//Run task1 after 5 seconds (nonblocking) - using Runnable
es1.schedule(task1, 5, TimeUnit.SECONDS);
// Run a task. The task has a result kept in the future object
Future<Integer> schedule = es1.submit(task2);
// block and get the result
System.out.println("1st get = "+schedule.get());
// initial Delay = 5, repeat the task every 1 second
ScheduledFuture<?> scheduledFuture = es1.scheduleAtFixedRate(task3, 5, 1, TimeUnit.SECONDS);
// Stop the Executor Service
es1.shutdown();
System.out.println("--------------------------------------------");
}
}
Info
shutdown()
- shutdowns the Executor Service - no new tasks are accepted, it waits for previously submitted tasks to complete execution.shutdownNow()
- forcibly, attempts to stop all actively executing tasks, and returns a list of the tasks that were awaiting execution.