Principle analysis of timer ScheduledExecutorService

Keywords: Concurrent Programming thread pool

I. simple use

Environment: jdk8

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        ScheduledExecutorService executorService=new ScheduledThreadPoolExecutor(1);
        executorService.scheduleWithFixedDelay(()->{
            System.out.println(dtf.format(LocalDateTime.now()));
        },1,3, TimeUnit.SECONDS);

For timer usage in spring, click https://blog.csdn.net/yegeg/article/details/121654509

From the new ScheduledThreadPoolExecutor, we can see that our timer is also related to the thread pool. Next, let's look at the ScheduledThreadPoolExecutor class

  It extends ThreadPoolExecutor, which indicates that it is also a thread pool and implements ScheduledExecutorService. This interface defines the methods owned by the timer

public interface ScheduledExecutorService extends ExecutorService {

    /**
     * Creates and executes a one-shot action that becomes enabled
     * after the given delay.
     *
     */
    public ScheduledFuture<?> schedule(Runnable command,
                                       long delay, TimeUnit unit);

    /**
     * Creates and executes a ScheduledFuture that becomes enabled after the
     * given delay.
     */
    public <V> ScheduledFuture<V> schedule(Callable<V> callable,
                                           long delay, TimeUnit unit);

    /**
     * Creates and executes a periodic action that becomes enabled first
     * after the given initial delay, and subsequently with the given
     * period; that is executions will commence after
     * {@code initialDelay} then {@code initialDelay+period}, then
     * {@code initialDelay + 2 * period}, and so on.
     * If any execution of the task
     * encounters an exception, subsequent executions are suppressed.
     * Otherwise, the task will only terminate via cancellation or
     * termination of the executor.  If any execution of this task
     * takes longer than its period, then subsequent executions
     * may start late, but will not concurrently execute.
     */
    public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
                                                  long initialDelay,
                                                  long period,
                                                  TimeUnit unit);

    /**
     * Creates and executes a periodic action that becomes enabled first
     * after the given initial delay, and subsequently with the
     * given delay between the termination of one execution and the
     * commencement of the next.  If any execution of the task
     * encounters an exception, subsequent executions are suppressed.
     * Otherwise, the task will only terminate via cancellation or
     * termination of the executor.
     */
    public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
                                                     long initialDelay,
                                                     long delay,
                                                     TimeUnit unit);

}

The commonly used sheldule, fixedRate and fixedDelay are stated in advance here

Second, what is the relationship between ScheduledExecutorService and thread pool

We know from the ScheduledThreadPoolExecutor class   ScheduledExecutorService inherits from ThreadPoolExecutor, so our scheduled tasks are also executed by the rules in the thread pool. In this article, we focus on ScheduledExecutorService. Now let's look at the scheduleWithFixedDelay source code of ScheduledThreadPoolExecutor

 public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
                                                     long initialDelay,
                                                     long delay,
                                                     TimeUnit unit) {
        if (command == null || unit == null)
            throw new NullPointerException();
        if (delay <= 0)
            throw new IllegalArgumentException();
         // ①
        ScheduledFutureTask<Void> sft =
            new ScheduledFutureTask<Void>(command,
                                          null,
                                          triggerTime(initialDelay, unit),
                                          unit.toNanos(-delay));
         
        RunnableScheduledFuture<Void> t = decorateTask(command, sft);// ②
        sft.outerTask = t;
        delayedExecute(t);  // ③
        return t;
    }

This function mainly does three things  

① Wrap our execution tasks, delays, and execution cycles into ScheduledFutureTask

The sequenceNumber task is incremented when it is created. If the execution time of two tasks is the same, you can judge which task is executed first according to this variable

Time task execution requires waiting time

period execution cycle. A positive number indicates a fixedRate task, a negative number indicates a fixedDelay task, and 0 indicates a non repetitive task

② The decorateTask method is implemented, which is mainly used as an extension point to allow users to modify and replace tasks

③ Put the task into a queue through delayedExecute, and ensure that at least one thread starts executing through the ensueprestart method. Ensueprestart is a thread pool method, which ensures that threads can start to execute tasks. The principle of thread pool will be analyzed in the online process pool article

private void delayedExecute(RunnableScheduledFuture<?> task) {
        if (isShutdown())
            reject(task);
        else {
            super.getQueue().add(task);
            if (isShutdown() &&
                !canRunInCurrentRunState(task.isPeriodic()) &&
                remove(task))
                task.cancel(false);
            else
                ensurePrestart();
        }
    }

Here, the task is encapsulated into a task and placed in the queue, and the thread is started to execute.

Third, how does it implement periodic calls

Through the above, we put the task in the queue and start the Thread to execute. How does it execute? We know that when starting a task with Thread, the task can implement the Runnable interface, and then execute its run. We said that the encapsulated ScheduledFutureTask also implements the Runnable interface, so when the Thread is executing, Run will also be executed. Let's look at overriding the run method in ScheduledFutureTask

 public void run() {
            boolean periodic = isPeriodic();//①
            if (!canRunInCurrentRunState(periodic))
                cancel(false);
            else if (!periodic)
                ScheduledFutureTask.super.run();// ②
            else if (ScheduledFutureTask.super.runAndReset()) { // ③
                setNextRunTime();
                reExecutePeriodic(outerTask); 
            }
        }

① This is to judge whether it is a periodic task. If the variable period of ScheduledFutureTask is not equal to 0, it indicates a periodic task

② If it is a one-time task, execute ScheduledFutureTask.super.run(). When this method is executed, run in futuretask will be executed. It calls the tasks we write to perform, which is understood as performing our own tasks.

③ If it is a periodic task, execute ScheduledFutureTask.super.runAndReset() and get the next execution time. Let's first see what runAndReset is. It is also a method in FutrueTask. After executing this method, it will be reset to the initial state.

setNextRunTime() to set the waiting time for the next execution of our task, which reflects the difference between the execution cycles of fixedRate and fixedDelay.

reExecutePeriodic puts our tasks back on the queue and starts a thread to execute

void reExecutePeriodic(RunnableScheduledFuture<?> task) {
        if (canRunInCurrentRunState(true)) {
            super.getQueue().add(task);
            if (!canRunInCurrentRunState(true) && remove(task))
                task.cancel(false);
            else
                ensurePrestart();
        }
    }

In this way, we can call our task periodically, put it in the queue -- > call the task -- > calculate the next execution time -- > put it in the team -- > call the task -- > calculate the next execution time

IV. how to obtain the tasks to be performed

From the above analysis, we know how tasks are executed periodically, and we also know that each task has a waiting time. So how do we get the task with the shortest waiting time to be executed, and what does the thread do during this waiting time? A queue called DelayedWorkQueue is used here. It is a blocking queue. The threads in the thread pool will get the task to be executed through their token. The token method will block until they can get the task to be executed recently. The task is placed in a minimum heap. The top of the heap is the task with the least waiting time. If the task waiting time has not arrived, The thread will be blocked and the cup will be released

Think about it

How does the DelayedWorkQueue achieve minimum heap storage when adding and removing tasks

When calling take, how does it block the thread and wake it up

Posted by infusionstudios on Fri, 03 Dec 2021 15:25:57 -0800