Java. util. concurrent package source code reading 14 thread pool series ScheduledThreadPoolExecutor Part 1 threadpoolexecutor

Source: Internet
Author: User

Java. util. concurrent package source code reading 14 thread pool series ScheduledThreadPoolExecutor Part 1 threadpoolexecutor

ScheduledThreadPoolExecutor is a subclass of ThreadPoolExecutor and implements the ScheduledExecutorService interface.

public class ScheduledThreadPoolExecutor        extends ThreadPoolExecutor        implements ScheduledExecutorService

 

ScheduledThreadPoolExecutor has two main functions: execution at a fixed point in time (or delayed execution) and repeated execution.

As with the analysis of ThreadPoolExecutor, the core method is execute:

    public void execute(Runnable command) {        schedule(command, 0, TimeUnit.NANOSECONDS);    }

The execute method calls another method schedule. At the same time, we find that the three submit methods also call the schedule method, because there are two types of tasks: Callable and Runnable, therefore, schedule also has two overload methods.

    public ScheduledFuture<?> schedule(Runnable command,                                       long delay,                                       TimeUnit unit) {        if (command == null || unit == null)            throw new NullPointerException();        RunnableScheduledFuture<?> t = decorateTask(command,            new ScheduledFutureTask<Void>(command, null,                                          triggerTime(delay, unit)));        delayedExecute(t);        return t;    }    public <V> ScheduledFuture<V> schedule(Callable<V> callable,                                           long delay,                                           TimeUnit unit) {        if (callable == null || unit == null)            throw new NullPointerException();        RunnableScheduledFuture<V> t = decorateTask(callable,            new ScheduledFutureTask<V>(callable,                                       triggerTime(delay, unit)));        delayedExecute(t);        return t;    }

The logic of the two methods is basically the same. They all wrap the task into a RunnableScheduledFuture object, and then call delayedExecute to implement delayed execution. The task packaging class inherits from the RunnableFuture packaging class of ThreadPoolExecutor, and implements the ScheduledFuture interface to enable delayed execution and repeated execution of these functions to match ScheduledThreadPoolExecutor.

So first, let's take a look at ScheduledFutureTask. The following are the specific variables of ScheduledFutureTask:

Private class ScheduledFutureTask <V> extends FutureTask <V> implements RunnableScheduledFuture <V >{/ ** serial number of all tasks in the thread pool */private final long sequenceNumber; /** the execution time from the start of the task, in the unit of nanoseconds */private long time;/*** the interval between repeated tasks, that is, the number of times at which the task is executed */private final long period;/** this type of object is used when the task is repeatedly executed and queued, */RunnableScheduledFuture <V> outerTask = this; /*** delay the queue index, which will speed up searching when the task is canceled */int heapIndex;

Let's look at the core method run:

Public void run () {boolean periodic = isPeriodic (); // checks whether a task can be run. Two other variables are involved: continueExistingPeriodicTasksAfterShutdown // and executeExistingDelayedTasksAfterShutdown // The former allows you to continue executing repetitive tasks after shutdown // The latter allows you to continue executing delayed tasks after shutdown, // This determines which option is used based on whether the task is periodic, and // If the thread pool is running, it can certainly be executed. // If the thread pool is shutdown, it depends on whether the option value is true to determine whether to allow task execution // if not, the task if (! CanRunInCurrentRunState (periodic) cancel (false); // if the task can be executed, else if (! Periodic) ScheduledFutureTask. super. run (); // for the task that needs to be executed repeatedly, execute it once, and then reset // update the next execution time of the worker, call reExecutePeriodic to update the else if (ScheduledFutureTask. super. runAndReset () {setNextRunTime (); reExecutePeriodic (outerTask );}}

 

So here we can get the implementation of repeated execution: The task is executed once, Reset status, and re-added to the task queue.

Return to delayedExecute, which ensures that the task is executed at an accurate point in time. It can be seen that if delayedExecute implements delayed execution:

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

At first glance, we can see how the delayed execution function is implemented by adding a task to the task queue. The secret is the implementation of the delayed execution function in the task queue.

    public ScheduledThreadPoolExecutor(int corePoolSize) {        super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS,              new DelayedWorkQueue());    }    public ThreadPoolExecutor(int corePoolSize,                              int maximumPoolSize,                              long keepAliveTime,                              TimeUnit unit,                              BlockingQueue<Runnable> workQueue) {        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,             Executors.defaultThreadFactory(), defaultHandler);    }

The task queue of ScheduledThreadPoolExecutor is not a common BlockingQueue, but a special implementation of DelayedWorkQueue. In the next article, we will talk about DelayedWorkQueue.




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.