Java Concurrency: ScheduledExecutorService

Category : Java | Sub Category : ExecutorService | By Prasad Bonam Last updated: 2021-04-20 03:26:58 Viewed : 770


The ScheduledExecutorService is an extended interface of ExecutorService.It is used to executes after given initial delay or execute tasks repeatedly with given intervals or both (both initial delay and repeatedly execution). 

It will repeatedly execute the task until it is explicitly stopped.

 

Different thread pool implementations

  • Single Thread for handling task. (with all repeated executions)
Executors.newSingleThreadScheduledExecutor();

As the name implies this will create only a single worker thread and it will be reused for all repeated execution.

Please refer the below example.


import java.util.concurrent.*;
public class Application
{
public static void main(String[] args) throws InterruptedException
{
System.out.println("main thread is started");
ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
scheduledExecutorService.scheduleAtFixedRate(() > {
System.out.println("Thread [" + Thread.currentThread().getName() + "] is executing the task");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("sleeping thread get interrupted");
}
}, 5, 2, TimeUnit.SECONDS);
}

}

The initial delay is 5 seconds and the interval between each execution is 2 seconds.

 

  • Thread pool for handling task (with repeated executions)
Executors.newScheduledThreadPool(5);

This will create a thread pool with five threads and those threads will be reused for all repeated execution. Each repeated execution will be handled by a randomly selected thread from the available thread pool.

Please refer the below example.

import java.util.concurrent.*;
public class Application
{
public static void main(String[] args) throws InterruptedException
{
System.out.println("main thread is started");
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(5);
scheduledExecutorService.scheduleAtFixedRate(() > {
System.out.println("Thread [" + Thread.currentThread().getName() + "] is executing the task");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("sleeping thread get interrupted");
}
}, 5, 2, TimeUnit.SECONDS);
}
}

Search
Related Articles

Leave a Comment: