"Java.util.concurrent package source reading" 14 thread pool series of Scheduledthreadpoolexecutor first part

Source: Internet
Author: User

Scheduledthreadpoolexecutor is a subclass of Threadpoolexecutor and implements the Scheduledexecutorservice interface.

 Public class Scheduledthreadpoolexecutor         extends Threadpoolexecutor         Implements Scheduledexecutorservice

There are two main functions of scheduledthreadpoolexecutor: Execution at a fixed point in time (also considered as deferred execution), repeated execution.

As in the analysis of Threadpoolexecutor, the core method of execute is first seen:

     Public void Execute (Runnable command) {        0, timeunit.nanoseconds);    }

The Execute method calls another method schedule, and we find that the three submit methods also call the schedule method, because there are two types of tasks: callable and runnable, so Schedule also has two overloaded methods.

     PublicScheduledfuture<?>Schedule (Runnable command,Longdelay, Timeunit unit) {        if(Command = =NULL|| Unit = =NULL)            Throw NewNullPointerException (); Runnablescheduledfuture<?> T =decoratetask (Command,NewScheduledfuturetask<void> (Command,NULL, Triggertime (delay, unit));        Delayedexecute (t); returnT; }     Public<V> scheduledfuture<v> Schedule (callable<v>Callable,Longdelay, Timeunit unit) {        if(Callable = =NULL|| Unit = =NULL)            Throw NewNullPointerException (); Runnablescheduledfuture<V> T =Decoratetask (callable,NewScheduledfuturetask<v>(callable, Triggertime (delay, unit)));        Delayedexecute (t); returnT; }

The two method logic is basically consistent, is to wrap the task into a runnablescheduledfuture object, and then call Delayedexecute to implement deferred execution. The task wrapper class inherits from the Threadpoolexecutor wrapper class Runnablefuture, Implementing the Scheduledfuture interface at the same time enables the wrapper class to defer execution and repeatedly perform these functions to match the scheduledthreadpoolexecutor.

So first look at Scheduledfuturetask, here are some of the Scheduledfuturetask proprietary variables:

Private classScheduledfuturetask<v>extendsFuturetask<v>ImplementsRunnablescheduledfuture<v> {        /**serial number for all tasks in the thread pool*/        Private Final LongSequenceNumber; /**the time, in nanoseconds, from which the task started executing*/        Private LongTime ; /*** Repeat the interval of the task, that is, how often to perform a task at a time*/        Private Final Longperiod; /**This type of object is used repeatedly to perform tasks and queues*/runnablescheduledfuture<V> Outertask = This; /*** The index of the delay queue, so that using the index when canceling the task will speed up the lookup*/        intHeapindex;

Look at the core method run:

         Public voidrun () {Booleanperiodic =Isperiodic (); //To detect if a task can be run, there are two other variables involved: Continueexistingperiodictasksaftershutdown//and Executeexistingdelayedtasksaftershutdown//The former allows repeated tasks to be performed after shutdown//The latter allows execution of deferred tasks after shutdown,//so depending on whether the task is periodic to decide which option to use, then//If the thread pool is running, you can certainly perform//If you are shutdown, see if the value of the option is true to decide whether to allow the task to be performed//if it's not allowed, the task will be canceled .            if(!canrunincurrentrunstate (periodic)) Cancel (false); //If you can perform a task, for a task that does not have to be repeated, execute it directly            Else if(!periodic) Scheduledfuturetask.Super. Run (); //for tasks that need to be repeated, execute once, and then reset//update the next execution time, call the Reexecuteperiodic Update task in the execution queue//location (which is actually added to the end of the queue)            Else if(Scheduledfuturetask.Super. Runandreset ())                {setnextruntime ();            Reexecuteperiodic (Outertask); }        }

So here's the implementation of a recurring implementation: The task executes once, the reset state, and rejoin the task queue.

Back to Delayedexecute, it ensures that the task executes at an accurate point in time, and to see if the Delayedexecute is implemented in a deferred way:

 private  void  Delayedexecute ( Runnablescheduledfuture<?> Task) { if
     (IsShutDown ()) reject (Task);  else   { super  .getqueue (). Add (Task);  if  (IsShutDown () &&!canrunincurrentrunstate (task.isper Iodic ()) && remove (Task)) Task.cancel ( false  );         else   Ensureprestart (); }    }

At first glance, the discovery is to add the task to the task queue, then the implementation of the delay function is how to implement, the secret is in the task queue implementation.

     PublicScheduledthreadpoolexecutor (intcorepoolsize) {        Super(Corepoolsize, Integer.max_value, 0, Timeunit.nanoseconds,Newdelayedworkqueue ()); }     PublicThreadpoolexecutor (intCorepoolsize,intMaximumpoolsize,LongKeepAliveTime, timeunit unit, Blockingqueue<Runnable>workQueue) {         This(Corepoolsize, maximumpoolsize, KeepAliveTime, Unit, WorkQueue, Executors.defaultthreadfactory (), Defaulth    Andler); }

Scheduledthreadpoolexecutor's task queue is not an ordinary blockingqueue, but a special implementation Delayedworkqueue. The next article is about this 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.