Java Concurrency: ScheduledExecutorService

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);
}
}

view raw
Application.java
hosted with ❤ by GitHub

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);
}
}

view raw
Application.java
hosted with ❤ by GitHub

 

 

One thought on “Java Concurrency: ScheduledExecutorService

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s