Skip to content
Related Articles

Related Articles

ScheduledThreadPoolExecutor Class in Java
  • Last Updated : 11 Sep, 2020

ScheduledThreadPoolExecutor class in Java is a subclass of ThreadPoolExecutor class defined in java.util.concurrent package. As it is clear from its name that this class is useful when we want to schedule tasks to run repeatedly or to run after a given delay for some future time.  It creates a fixed-sized Thread Pool. So when it is initiated, it needs to be given the corePoolSize (the number of threads in the Thread pool).

Class Hierarchy: 

ScheduledThreadPoolExecutor-Class-in-Java

Constructors:

  • ScheduledThreadPoolExecutor(int corePoolSize) : Creates a new ScheduledThreadPoolExecutor object with the given pool size. It is to be noted that it creates a fixed-sized Thread Pool so once the corePoolSize is given, one can not increase the size of the Thread Pool.
  • ScheduledThreadPoolExecutor(int corePoolSize, ThreadFactory threadFactory) : Creates a new ScheduledThreadPoolExecutor object with the given parameters. The first parameter is the size of the Thread Pool and the second parameter is a ThreadFactory object that is used when the ScheduledThreadPoolExecutor creates a new thread.
  • ScheduledThreadPoolExecutor(int corePoolSize, RejectedExecutionHandler handler): Creates a new ScheduledThreadPoolExecutor object with the given corePoolSize(ThreadPool size) and the handler that is used when the execution of a task is rejected (when the working queue is full or execution is blocked).
  • ScheduledThreadPoolExecutor(int corePoolSize, ThreadFactory threadFactory, RejectedExecutionHandler handler): Creates a new ScheduledThreadPoolExecutor object with the given parameters.

Besides these constructors, there is another way to get a ScheduledThreadPoolExecutor object. We can use Executors.newScheduledThreadPool(int corePoolSize) factory method defined by Executors class. It returns a ScheduledExecutorService object which can be type-casted to ScheduledThreadPoolExecutor object.



ScheduledThreadPoolExecutor threadPool = (ScheduledThreadPoolExecutor)Executors.newScheduledThreadPool(4);

Example 1:

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to demonstrates ScheduleThreadPoolExecutor
// class
import java.util.*;
import java.util.concurrent.*;
import java.io.*;
  
class GFG {
    public static void main(String[] args)
    {
  
        // Creating a ScheduledThreadPoolExecutor object
        ScheduledThreadPoolExecutor threadPool
            = new ScheduledThreadPoolExecutor(2);
  
        // Creating two Runnable objects
        Runnable task1 = new Command("task1");
        Runnable task2 = new Command("task2");
  
        // Printing the current time in seconds
        System.out.println(
            "Current time : "
            + Calendar.getInstance().get(Calendar.SECOND));
  
        // Scheduling the first task which will execute
        // after 2 seconds
        threadPool.schedule(task1, 2, TimeUnit.SECONDS);
  
        // Scheduling the second task which will execute
        // after 5 seconds
        threadPool.schedule(task2, 5, TimeUnit.SECONDS);
  
        // Remember to shut sown the Thread Pool
        threadPool.shutdown();
    }
}
  
// Class that implements the Runnable interface
class Command implements Runnable {
    String taskName;
    public Command(String taskName)
    {
        this.taskName = taskName;
    }
    public void run()
    {
        System.out.println(
            "Task name : " + this.taskName + " Current time: "
            + Calendar.getInstance().get(Calendar.SECOND));
    }
}

chevron_right


Output :

Current time : 51
Task name : task1 Current time : 53
Task name : task2 Current time : 56

Here the first task is executed after a two seconds delay and the second task is executed after the five seconds.

Example 2:

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to demonstrates ScheduleThreadPoolExecutor
// class
import java.util.*;
import java.util.concurrent.*;
import java.io.*;
  
class GFG {
    public static void main(String[] args)
    {
  
        // Creating a ScheduledThreadPoolExecutor object
        ScheduledThreadPoolExecutor threadPool
            = new ScheduledThreadPoolExecutor(2);
  
        // Creating two Runnable objects
        Runnable task1 = new Command("task1");
        Runnable task2 = new Command("task2");
  
        // Printing the current time in seconds
        System.out.println(
            "Current time:"
            + Calendar.getInstance().get(Calendar.SECOND));
  
        // Scheduling the first task which will execute
        // after 2 seconds and then repeats periodically with
        // a period of 8 seconds
        threadPool.scheduleAtFixedRate(task1, 2, 8,
                                       TimeUnit.SECONDS);
  
        // Scheduling the second task which will execute
        // after 5 seconds and then there will be a delay of
        // 5 seconds between the completion
        // of one execution and the commencement of the next
        // execution
        threadPool.scheduleWithFixedDelay(task2, 5, 5,
                                          TimeUnit.SECONDS);
  
        // Wait for 30 seconds
        try {
            Thread.sleep(30000);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
  
        // Remember to shut sown the Thread Pool
        threadPool.shutdown();
    }
}
  
// Class that implements Runnable interface
class Command implements Runnable {
    String taskName;
    public Command(String taskName)
    {
        this.taskName = taskName;
    }
    public void run()
    {
        try {
            System.out.println("Task name : "
                               + this.taskName
                               + " Current time : "
                               + Calendar.getInstance().get(
                                     Calendar.SECOND));
            Thread.sleep(2000);
            System.out.println("Executed : " + this.taskName
                               + " Current time : "
                               + Calendar.getInstance().get(
                                     Calendar.SECOND));
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}

chevron_right


Output :

Current time:26
Task name : task1 Current time : 28
Executed : task1 Current time : 30
Task name : task2 Current time : 31
Executed : task2 Current time : 33
Task name : task1 Current time : 36
Executed : task1 Current time : 38
Task name : task2 Current time : 38
Executed : task2 Current time : 40
Task name : task1 Current time : 44
Task name : task2 Current time : 45
Executed : task1 Current time : 46
Executed : task2 Current time : 47
Task name : task1 Current time : 52
Task name : task2 Current time : 52
Executed : task1 Current time : 54
Executed : task2 Current time : 54

Here, the first task will execute after the two seconds and then repeats periodically after the eight seconds. The second task will execute after the five seconds and then there will be a delay of five seconds between the completion of one execution and the commencement of the next execution.

Methods

METHOD

DESCRIPTION

decorateTask(Callable<V> callable, RunnableScheduledFuture<V> task) Modifies or replaces the task used to execute a callable.
decorateTask(Runnable runnable, RunnableScheduledFuture<V> task) Modifies or replaces the task used to execute a runnable.
execute(Runnable command) Executes command with zero required delay.
getContinueExistingPeriodicTasksAfterShutdownPolicy( ) Get the policy on whether to continue executing existing periodic tasks even when this executor has been shut down.
getExecuteExistingDelayedTasksAfterShutdownPolicy( ) Get the policy on whether to execute existing delayed tasks even when this executor has been shut down.
getQueue() Returns the task queue used by this executor.
getRemoveOnCancelPolicy() Gets the policy on whether cancelled tasks should be immediately removed from the work queue at the time of cancellation.
schedule(Callable<V> callable, long delay, TimeUnit unit) Creates and executes a ScheduledFuture that becomes enabled after the given delay.
schedule(Runnable command, long delay, TimeUnit unit) Creates and executes a one-shot action that becomes enabled after the given delay.
scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) Creates and executes a periodic action that becomes enabled first after the given delay and subsequently with the given period.
scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) Creates and executes a periodic action that becomes enabled after the given delay and subsequently with the given delay between the termination of one execution and commencement of the next execution.
setContinueExistingPeriodicTasksAfterShutdownPolicy(boolean value) Sets the policy on whether to continue executing existing periodic tasks even when this executor has been shut down.
setExecuteExistingDelayedTasksAfterShutdownPolicy(boolean value) Sets the policy on whether to execute existing delayed tasks even when this executor has been shut down.
setRemoveOnCancelPolicy() Sets the policy on whether cancelled tasks should be immediately removed from the work queue at the time of cancellation.
shutdown() Initiate an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted.
shutdownNow() Attempts to stop all actively executing tasks halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution.
submit(Callable<T> task) Submits a value returning task for execution and returns a future representing the pending results of the task.
submit(Runnable task) Submits a runnable task for execution and returns a future representing that task.
submit(Runnable task, T result) Submits a runnable task for execution and returns a future representing that task.

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :