Timer and scheduledthreadpoolexecutor

Source: Internet
Author: User

In practical applications, sometimes we need to create some delayed and periodic tasks. For example, we want to make a log every one hour after our program starts. JDK provides two methods to create delayed periodic tasks.


TimerTimer is Java. A class under the util package was introduced during jdk1.3. Timer only acts as an executor. The real task logic is completed through an abstract class called timertask, and timertask is also Java. the class under the util package is an abstract class that implements the runnable interface and contains an abstract method run (). We need to provide specific business implementation by ourselves. The timer class object executes the business logic defined in the timertask object through its schedule method, and the schedule method has multiple overload methods to provide different latency and periodic services.
The following is a delayed periodic task created using Timer:
import java.text.SimpleDateFormat;import java.util.Date;import java.util.Timer;import java.util.TimerTask;public class TestTimer {public static void main(String[] args) {String time = new SimpleDateFormat("HH:mm:ss").format(new Date());System.out.println("Start time : " + time);Timer timer = new Timer();TimerTask task = new TimerTask() {@Overridepublic void run() {// TODO Auto-generated method stubString time = new SimpleDateFormat("HH:mm:ss").format(new Date());System.out.println("Now Time : "  + time);}}; //end tasktimer.schedule(task, 2000, 3000);}}

Program output:
Start time : 21:36:08Now Time : 21:36:10Now Time : 21:36:13Now Time : 21:36:16Now Time : 21:36:19

ScheduledthreadpoolexecutorIn jdk1.5. util. the scheduledthreadpoolexecutor class is introduced under the concurrent package because the delayed periodic tasks created by the Timer class have some defects. scheduledthreadpoolexecutor inherits threadpoolexecutor and implements the scheduledexecutorservice interface, scheduledthreadpoolexecutor also executes the runnable task using the schedule method. We use scheduledthreadpoolexecutor to implement the same functions as the above timer.
Import Java. text. simpledateformat; import Java. util. date; import Java. util. concurrent. scheduledthreadpoolexecutor; import Java. util. concurrent. timeunit; public class testscheduledthreadpoolexecutor {public static void main (string [] ARGs) {string time = new simpledateformat ("HH: mm: SS "). format (new date (); system. out. println ("Start Time:" + time); scheduledthreadpoolexecutor executor = new scheduledthreadpoolexecutor (5); // create five execution threads runnable = new runnable () {@ overridepublic void run () {// todo auto-generated method stubstring time = new simpledateformat ("HH: mm: SS "). format (new date (); system. out. println ("now time:" + time) ;}}; executor. schedulewithfixeddelay (runnable, 2, 3, timeunit. seconds );}}

Program output:
Start time : 22:12:25Now Time : 22:12:27Now Time : 22:12:30Now Time : 22:12:33Now Time : 22:12:36

In this case, it seems that there is no declared difference between timer and scheduledthreadpoolexecutor, but the introduction of scheduledthreadpoolexecutor is due to some shortcomings of the Timer class, and in jdk1.5 or higher, Timer classes are hardly used, the following describes some shortcomings of timer.
Single threadThe timer class executes all timertask tasks through a single thread. If the execution process of a task is very time-consuming, the timeliness of other tasks may occur. Scheduledthreadpoolexecutor is a thread-based multi-thread execution task. Here we will explain by letting timer execute two timertask tasks. The execution process of one timertask is time-consuming and it takes 2 seconds to add it.
import java.text.SimpleDateFormat;import java.util.Date;import java.util.Timer;import java.util.TimerTask;public class SingleThreadTimer {public static void main(String[] args) {String time = new SimpleDateFormat("HH:mm:ss").format(new Date());System.out.println("Start time : " + time);Timer timer = new Timer();TimerTask task1 = new TimerTask() {@Overridepublic void run() {// TODO Auto-generated method stubString time = new SimpleDateFormat("HH:mm:ss").format(new Date());System.out.println("Task1 time : " + time);}};TimerTask task2 = new TimerTask() {@Overridepublic void run() {// TODO Auto-generated method stubtry {Thread.sleep(2000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}String time = new SimpleDateFormat("HH:mm:ss").format(new Date());System.out.println("task2 time : " + time);}};timer.schedule(task1, 2000, 1000);timer.schedule(task2, 2000, 3000);}}

Two tasks are defined here: Task 1, run every 1 second after the program starts for 2 seconds, Task 2, and run once every 3 seconds after the program starts for 2 seconds, then let timer run the output of the two Task programs at the same time as follows:
Start time : 22:22:37Task1 time : 22:22:39task2 time : 22:22:41Task1 time : 22:22:41Task1 time : 22:22:42task2 time : 22:22:44Task1 time : 22:22:44Task1 time : 22:22:45task2 time : 22:22:47Task1 time : 22:22:47Task1 time : 22:22:48

It can be analyzed that neither Task 1 nor Task 2 runs as expected. The reason for this phenomenon is that the Timer class is single-threaded.
Timer thread does not capture exceptionsThe timer class does not capture exceptions. If an unchecked exception is thrown in a timertask (p.s: Exceptions in Java are classified into two types: checked exception (check exceptions) and unchecked exception (uncheckexception). For an unchecked exception, it is also called runtimeexception (runtime exception ).), the timer class will not handle this exception and cause unexpected errors. If such a task throws an exception, the entire timer task will be canceled. At this time, the scheduled but unexecuted timertask will never be executed, new tasks cannot be scheduled (so-called "thread leakage ). The following describes the common runtimeexception and arrayindexoutofboundsexception array out-of-bounds exception to demonstrate this disadvantage:
import java.text.SimpleDateFormat;import java.util.Date;import java.util.Timer;import java.util.TimerTask;public class TestTimerTask {public static void main(String[] args) {System.out.println(new SimpleDateFormat("HH:mm:ss").format(new Date()));Timer timer = new Timer();TimerTask task1 = new TimerTask() {@Overridepublic void run() {System.out.println("1: " + new SimpleDateFormat("HH:mm:ss").format(new Date()));}};TimerTask task2 = new TimerTask() {@Overridepublic void run() {int[] arr = {1,2,3,4,5};try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}int index = (int)(Math.random()*100);System.out.println(arr[index]);System.out.println("2: " + new SimpleDateFormat("HH:mm:ss").format(new Date()));}};timer.schedule(task1, 2000, 3000);timer.schedule(task2, 2000, 1000);}}

The program throws an array out-of-bounds exception during running, and the entire program is terminated. The original intact Task 1 is also terminated.
Based on absolute timeTimer class scheduling is based on absolute time, rather than relative time. Therefore, Timer class is sensitive to system clock changes. For example, you want to execute Task 1 every 10 seconds. At a time point, if you advance the system time by 6 seconds, Task 1 will be executed after 4 seconds instead of 10 seconds. In scheduledthreadpoolexecutor, task scheduling is based on relative time, the reason is that it stores the time required for the task to be scheduled next time in the task (the relative time implemented based on system # nanotime is used and will not be changed because of system time changes, if there are 10 seconds before the next execution, it will not be changed to 4 seconds after the first 6 seconds of the system time ).
Based on the above three drawbacks, in jdk1.5 or later versions, we have almost no reason to continue using the Timer class. scheduledthreadpoolexecutor can effectively replace the Timer class to complete delayed periodic tasks.






Timer and scheduledthreadpoolexecutor

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.