Detailed description of Timer and TimerTask in JDK

Source: Internet
Author: User
Tags thread stop

Directory structure:

  • Timer and TimerTask
  • Example of Timer Scheduling
  • How to terminate a Timer thread
  • About the cancle method to terminate a thread
  • Execute a task repeatedly
  • Schedule VS. scheduleAtFixedRate
  • Notes

1. Timer and TimerTask

Timer is a Timer tool provided by jdk. When used, it starts a separate thread outside the main thread to execute the specified scheduled task. It can be executed once or repeatedly multiple times.

TimerTask is an abstract class that implements the Runnable interface and represents a task that can be executed by Timer.

2. Example of Timer Scheduling

 1 import java.util.Timer; 2 import java.util.TimerTask; 3  4 public class TestTimer { 5      6     public static void main(String args[]){ 7         System.out.println("About to schedule task."); 8         new Reminder(3); 9         System.out.println("Task scheduled.");10     }11     12     public static class Reminder{13         Timer timer;14         15         public Reminder(int sec){16             timer = new Timer();17             timer.schedule(new TimerTask(){18                 public void run(){19                     System.out.println("Time's up!");20                     timer.cancel();21                 }22             }, sec*1000);23         }24     } 25 }

After running, the following information is displayed on the console:

About to schedule task.
Task scheduled.

Then 3 seconds later

Time's up!

From this example, we can see that a typical process of using timer to execute scheduled tasks is as follows:

  • A new TimerTask subclass is used to override the run method to specify a specific task. In this example, I used an anonymous internal class to implement a subclass of TimerTask.
  • A new Timer class. The Timer constructor starts a separate thread to execute the scheduled task. The jdk implementation code is as follows:
1     public Timer() {2         this("Timer-" + serialNumber());3     }4 5     public Timer(String name) {6         thread.setName(name);7         thread.start();8     }
  • Call the relevant scheduling method execution plan. In this example, the schedule method is called.
  • The task is completed and the thread is terminated. In this example, the cancel method is called to end the thread.

3. How to terminate the Timer thread

By default, the created timer thread is always executed. There are four methods to terminate the timer thread:

  • Call the timer cancle Method
  • Set the timer thread to a daemon thread (new Timer (true) to create a daemon thread). In jvm, if all user threads end, the daemon thread will also be terminated, however, this method is generally not used.
  • When all tasks are completed, the reference of the corresponding timer object is deleted, and the thread is terminated.
  • Call the System. exit method to terminate the program.

4. terminate a thread in cancle Mode

To terminate the timer thread in this way, jdk implementation is clever.

First, let's look at the source code of the cancle method:

1     public void cancel() {2         synchronized(queue) {3             thread.newTasksMayBeScheduled = false;4             queue.clear();5             queue.notify();  // In case queue was already empty.6         }7     }

There is no explicit thread stop method. Instead, the clear method of queue and the notify method of queue are called. clear is a custom method, and notify is a built-in method of Objec, it is obvious that the wait method is wake up.

Let's look at the clear method again:

1     void clear() {2         // Null out task references to prevent memory leak3         for (int i=1; i<=size; i++)4             queue[i] = null;5 6         size = 0;7     }

The clear method is very simple, that is, to clear the queue, the queue is an array of TimerTask, and then reset the size of the queue to 0 to empty. we still don't see the explicit stop thread method. When we get back to the new Timer, let's look at the new Timer code:

1     public Timer() {2         this("Timer-" + serialNumber());3     }4 5     public Timer(String name) {6         thread.setName(name);7         thread.start();8     }

Check out the Internal Variable thread:

1     /**2      * The timer thread.3      */4     private TimerThread thread = new TimerThread(queue);

Not a native Thread, It is a custom class TimerThread. This class implements the Thread class and overwrites the run method, as shown below:

 1     public void run() { 2         try { 3             mainLoop(); 4         } finally { 5             // Someone killed this Thread, behave as if Timer cancelled 6             synchronized(queue) { 7                 newTasksMayBeScheduled = false; 8                 queue.clear();  // Eliminate obsolete references 9             }10         }11     }

The last is the mainLoop method, which is relatively long and takes the first part:

 1     private void mainLoop() { 2         while (true) { 3             try { 4                 TimerTask task; 5                 boolean taskFired; 6                 synchronized(queue) { 7                     // Wait for queue to become non-empty 8                     while (queue.isEmpty() && newTasksMayBeScheduled) 9                         queue.wait();10                     if (queue.isEmpty())11                         break; // Queue is empty and will forever remain; die

We can see that the wait method, the previous commit y is to notify this wait, and then the clear method clears the array before commit y, so it will break, thread execution ends, exit.

5. Execute a task repeatedly

It is implemented by calling the schedule method of the three parameters. The last parameter is the execution interval, in milliseconds.

6. schedule VS. scheduleAtFixedRate

The two methods are both job scheduling methods. The difference between them is that schedule will ensure that the job interval is strictly executed according to the defined period parameter. if a job is scheduled for a long time, the subsequent time will be postponed to ensure the scheduling interval is period, while scheduleAtFixedRate is strictly based on the scheduling time. If a scheduling time is too long, the interval is shortened to ensure that the next scheduling is executed at the specified time. For example, if you schedule a task every 3 seconds, the scheduled task is as follows:, 6, and 9 seconds. If the second scheduling takes 2 seconds, it will change to +, 11, and ensure the interval, while scheduleAtFixedRate will change to +, 9, compression interval, and ensure the scheduling time.

7. Notes

  • Each Timer corresponds to only one thread.
  • Timer does not guarantee that the task execution is very accurate.
  • Timer class thread security.

Related Article

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: 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.