ScheduleThreadPoolExecutor source code analysis, jquery source code analysis

Source: Internet
Author: User

ScheduleThreadPoolExecutor source code analysis, jquery source code analysis

ScheduleThreadPoolExecutor source code analysis (1)

In Java, ScheduleThreadPoolExecutor is mainly used to execute delayed tasks or execute tasks at a certain frequency. The scheduleAtFixedRate function executes tasks at a certain frequency. scheduleWithFixedDelay can execute tasks based on a certain delay. This article analyzes why ScheduleThreadPoolExecutor supports latency and executes tasks at a fixed frequency by referring to the source code of ScheduleThreadPoolExecutor.

ScheduleThreadPoolExecutor depends on the two internal classes encapsulated by ScheduledFutureTask and DelayedWorkQueue to perform tasks at a certain frequency. ScheduledFutureTask inherits the FutureTask class, so it can encapsulate tasks that inherit the Runable or Callable interfaces. The DelayedWorkQueue is a latency queue. It uses the minimal heap implementation and requires the first task to be executed at the top of the heap, So that you only need to obtain the task at the top of the heap for each task execution.

ScheduledFutureTask:

ScheduledFutureTask inherits FutureTask, so it can be executed by ScheduledExecutorService. The following describes some important attributes of ScheduledFutureTask:

  • Int heapIndex: indicates the index of the task in the DelayedWorkQueue queue. Because DelayedWorkQueue is built by the smallest heap, in order to improve the search speed, this field is introduced into the encapsulated Task to reduce the search time complexity to O (1 ).
  • Private long time: the execution time of the task. In the getDelay () function, it takes a long time to obtain the task execution time according to unit. convert (time-now (), NANOSECONDS. At the same time, in DelayedWorkQueue, the minimum heap is maintained based on this field.
  • Private final long period: the time when duplicate tasks are executed. A positive number indicates that the task is executed at a certain rate, a negative number indicates that the task is executed at a certain delay, and 0 indicates that the task is not executed repeatedly.
  • RunnableScheduledFuture outerTask = this: specifies this task.
  • Private final long sequenceNumber: the sequence in which tasks enter the queue, ensuring the FIFO of the queue

The main methods of ScheduledFutureTask are compareTo, getDelay, and setNextRunTime.

  •   public long getDelay(TimeUnit unit) {    return unit.convert(time - now(), NANOSECONDS);}

    This method is mainly used to obtain the delay time when the task needs to be executed. It is used in the offer function of DelayedWorkQueue.

    public int compareTo(Delayed other) {    if (other == this) // compare zero if same object        return 0;    if (other instanceof ScheduledFutureTask) {        ScheduledFutureTask<?> x = (ScheduledFutureTask<?>)other;        long diff = time - x.time;        if (diff < 0)            return -1;        else if (diff > 0)            return 1;        else if (sequenceNumber < x.sequenceNumber)            return -1;        else            return 1;    }    long diff = getDelay(NANOSECONDS) - other.getDelay(NANOSECONDS);    return (diff < 0) ? -1 : (diff > 0) ? 1 : 0;}

    The compareTo method is mainly used to sort the smallest heap in the DelayQueue. It is determined based on the task execution time. If the task execution time is the same, it is determined according to the FIFO rule of the queue.

  •   private void setNextRunTime() {    long p = period;    if (p > 0)        time += p;    else        time = triggerTime(-p);}

    The setNextRunTIme () method mainly sets the next execution time for the task that needs to be executed repeatedly. When the period is greater than 0, the task is executed at a certain rate, you only need to add the execution time to the interval. When the period is <0, the task is postponed and triggerTime must be called to obtain the next execution time. The implementation of the triggerTime function is as follows:

    long triggerTime(long delay) {return now() +    ((delay < (Long.MAX_VALUE >> 1)) ? delay : overflowFree(delay));}/*** Constrains the values of all delays in the queue to be within * Long.MAX_VALUE of each other, to avoid overflow in compareTo.* This may occur if a task is eligible to be dequeued, but has* not yet been, while some other task is added with a delay of* Long.MAX_VALUE.*/private long overflowFree(long delay) {Delayed head = (Delayed) super.getQueue().peek();if (head != null) {    long headDelay = head.getDelay(NANOSECONDS);    if (headDelay < 0 && (delay - headDelay < 0))        delay = Long.MAX_VALUE + headDelay;    }    return delay;}

    The code above shows that the execution time of delayed tasks is the current time plus the delay time. In order to prevent the duration from being too large, the delay time is obtained based on the execution time of the next task to be executed in the queue. The next article describes the detailed implementation of DelayQueue.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.