Java Timer Timer principle

Source: Internet
Author: User

Do projects often use timed tasks, such as late at night, when the traffic is small, do some statistical work. Send emails, update databases, etc. in the morning. This can be implemented with a Java timer or thread pool. The timer can be implemented, but there are some problems with the timer. He plays a single thread, and if there are exceptions, the threads will exit and the entire scheduled task will fail.

Here is a timer implementation of the timer task demo, will be output to the console every second ...

1 Importjava.util.Date;2 ImportJava.util.Timer;3 ImportJava.util.TimerTask;4 5 /**6 * Created by GXF on 2017/6/21.7  */8  Public classTesttimer {9      Public Static voidMain (string[] args) {TenTimer timer =NewTimer (); OneTask task =NewTask (); ATimer.schedule (Task,NewDate (), 1000); -     } - } the  - classTaskextendstimertask{ -  - @Override +      Public voidrun () { -System.out.println ("Do work ..."); +     } A}

Console output

Do work ... Do work ... Do work ... Do work ...

We will enter the JDK source code analysis, Timer principle

Timer source

 Public classTimer {/*** the timer task queue.  This data structure is a shared with the timer * thread. The timer produces tasks, via its various schedule calls, * and the timer thread consumes, executing timer tasks as AP     Propriate, * and removing them from the queue when they ' re obsolete. */    Private FinalTaskqueue queue =NewTaskqueue (); /*** the timer thread. */    Private FinalTimerThread thread =NewTimerThread (queue);

As you can see here, there is a queue (actually a minimal heap), and a thread object

We're looking at the timer's constructor.

/**      * Creates a new timer.  The associated thread does <i>not</i>     * {@linkplain  Thread#setdaemon Run as a daemon} .      */     Public Timer () {        this ("timer-" + serialnumber ());    } 

Here we call the parameter constructor and go to the view

/**      * Creates a new timer whose associated thread has the the specified name.     * The associated thread does <i>not</i>     * {@linkplain  Thread#setdaemon Run as a daemon} .     *     @param  Name The name of the associated thread     @throws  NullPointerException if {@code  name} is null     @since  1.5      */     Public Timer (String name) {        thread.setname (name);        Thread.Start ();    }

Here you can see that a thread has started

OK, let's take a look again, timertask this class

/**@author@see@since*           /publicabstractclassimplements Runnable {

Although the code is not too much, and does not post, it is seen here, is a class that implements the Runable interface, that is, can be put into the thread to run the task

It is clear here that the timer is a thread, and TimerTask is a runable implementation class that can run the task as long as the TimerTask object is committed.

 Public void Long period) {        if (period <= 0)            thrownew illegalargumentexception (" Non-positive period. " );         -period);    }

Enter timer shed (task, firsttime, period)

Private voidSched (timertask task,LongTimeLongperiod) {        if(Time < 0)            Throw NewIllegalArgumentException ("Illegal execution time."); //constrain value of period sufficiently to prevent numeric//overflow while still being effectively infinitely large.        if(Math.Abs (Period) > (long.max_value >> 1)) Period>>= 1; synchronized(queue) {if(!thread.newtasksmaybescheduled)Throw NewIllegalStateException ("Timer already cancelled.")); synchronized(task.lock) {if(Task.state! =timertask.virgin)Throw NewIllegalStateException ("Task already scheduled or cancelled"); Task.nextexecutiontime=Time ; Task.period=period; Task.state=timertask.scheduled;            } queue.add (Task); if(queue.getmin () = =Task) queue.notify (); }    }

Here the main is Queue.add (Task) puts the task into the smallest heap, and queue.notity () wakes up on the waiting thread

Then we go into the Timer class TimerThread object to see the Run method, because there is a TimerThread object in the Timer class is a thread

 Public void run () {        try  {            mainloop ();         finally {            //  Someone killed this Thread, behave as if Timer cancelled             Synchronized(queue) {                false;                Queue.clear ();   // eliminate obsolete references             }        }    }

As can be seen here, in executing a mainloop () loop, enter this loop

/*** The main timer loop.     (see class comment.) */    Private voidMainloop () { while(true) {            Try{timertask task; Booleantaskfired; synchronized(queue) {//Wait for the queue to become Non-empty                     while(Queue.isempty () &&newtasksmaybescheduled) queue.wait (); if(Queue.isempty ()) Break;//Queue is empty and would forever remain;//Queue nonempty; look at first evt and does the right thing                    LongCurrentTime, ExecutionTime; Task=queue.getmin (); synchronized(task.lock) {if(Task.state = =timertask.cancelled) {queue.removemin (); Continue;//No action required, poll queue again} currenttime=System.currenttimemillis (); ExecutionTime=Task.nextexecutiontime; if(taskfired = (executiontime<=currenttime)) {                            if(Task.period = = 0) {//non-repeating, removequeue.removemin (); Task.state=timertask.executed; } Else{//repeating task, rescheduleQueue.reschedulemin (Task.period<0? CurrentTime-Task.period:executionTime+task.period); }                        }                    }                    if(!taskfired)//Task hasn ' t yet fired; waitQueue.wait (ExecutionTime-currenttime); }                if(taskfired)//Task fired; run it, holding no locksTask.run (); } Catch(Interruptedexception e) {}}

It is forgotten here that the timertask is sorted by Nextexecutiontime heap. Each time the heap is nextexecutiontime compared to the current system time, if the current time is greater than nextexecutiontime execution, if it is a single task, the task will be removed from the smallest heap. Otherwise, update the value of Nextexecutiontime

At this point, the Timer task principle basic understanding, single thread + minimum heap + continuous polling

Java Timer Timer principle

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.