Home | History | Annotate | Download | only in util
      1 /*
      2  * Copyright (c) 1999, 2008, Oracle and/or its affiliates. All rights reserved.
      3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
      4  *
      5  * This code is free software; you can redistribute it and/or modify it
      6  * under the terms of the GNU General Public License version 2 only, as
      7  * published by the Free Software Foundation.  Oracle designates this
      8  * particular file as subject to the "Classpath" exception as provided
      9  * by Oracle in the LICENSE file that accompanied this code.
     10  *
     11  * This code is distributed in the hope that it will be useful, but WITHOUT
     12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
     13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
     14  * version 2 for more details (a copy is included in the LICENSE file that
     15  * accompanied this code).
     16  *
     17  * You should have received a copy of the GNU General Public License version
     18  * 2 along with this work; if not, write to the Free Software Foundation,
     19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
     20  *
     21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
     22  * or visit www.oracle.com if you need additional information or have any
     23  * questions.
     24  */
     25 
     26 package java.util;
     27 import dalvik.annotation.optimization.ReachabilitySensitive;
     28 import java.util.Date;
     29 import java.util.concurrent.atomic.AtomicInteger;
     30 
     31 /**
     32  * A facility for threads to schedule tasks for future execution in a
     33  * background thread.  Tasks may be scheduled for one-time execution, or for
     34  * repeated execution at regular intervals.
     35  *
     36  * <p>Corresponding to each <tt>Timer</tt> object is a single background
     37  * thread that is used to execute all of the timer's tasks, sequentially.
     38  * Timer tasks should complete quickly.  If a timer task takes excessive time
     39  * to complete, it "hogs" the timer's task execution thread.  This can, in
     40  * turn, delay the execution of subsequent tasks, which may "bunch up" and
     41  * execute in rapid succession when (and if) the offending task finally
     42  * completes.
     43  *
     44  * <p>After the last live reference to a <tt>Timer</tt> object goes away
     45  * <i>and</i> all outstanding tasks have completed execution, the timer's task
     46  * execution thread terminates gracefully (and becomes subject to garbage
     47  * collection).  However, this can take arbitrarily long to occur.  By
     48  * default, the task execution thread does not run as a <i>daemon thread</i>,
     49  * so it is capable of keeping an application from terminating.  If a caller
     50  * wants to terminate a timer's task execution thread rapidly, the caller
     51  * should invoke the timer's <tt>cancel</tt> method.
     52  *
     53  * <p>If the timer's task execution thread terminates unexpectedly, for
     54  * example, because its <tt>stop</tt> method is invoked, any further
     55  * attempt to schedule a task on the timer will result in an
     56  * <tt>IllegalStateException</tt>, as if the timer's <tt>cancel</tt>
     57  * method had been invoked.
     58  *
     59  * <p>This class is thread-safe: multiple threads can share a single
     60  * <tt>Timer</tt> object without the need for external synchronization.
     61  *
     62  * <p>This class does <i>not</i> offer real-time guarantees: it schedules
     63  * tasks using the <tt>Object.wait(long)</tt> method.
     64  *
     65  * <p>Java 5.0 introduced the {@code java.util.concurrent} package and
     66  * one of the concurrency utilities therein is the {@link
     67  * java.util.concurrent.ScheduledThreadPoolExecutor
     68  * ScheduledThreadPoolExecutor} which is a thread pool for repeatedly
     69  * executing tasks at a given rate or delay.  It is effectively a more
     70  * versatile replacement for the {@code Timer}/{@code TimerTask}
     71  * combination, as it allows multiple service threads, accepts various
     72  * time units, and doesn't require subclassing {@code TimerTask} (just
     73  * implement {@code Runnable}).  Configuring {@code
     74  * ScheduledThreadPoolExecutor} with one thread makes it equivalent to
     75  * {@code Timer}.
     76  *
     77  * <p>Implementation note: This class scales to large numbers of concurrently
     78  * scheduled tasks (thousands should present no problem).  Internally,
     79  * it uses a binary heap to represent its task queue, so the cost to schedule
     80  * a task is O(log n), where n is the number of concurrently scheduled tasks.
     81  *
     82  * <p>Implementation note: All constructors start a timer thread.
     83  *
     84  * @author  Josh Bloch
     85  * @see     TimerTask
     86  * @see     Object#wait(long)
     87  * @since   1.3
     88  */
     89 
     90 public class Timer {
     91     /**
     92      * The timer task queue.  This data structure is shared with the timer
     93      * thread.  The timer produces tasks, via its various schedule calls,
     94      * and the timer thread consumes, executing timer tasks as appropriate,
     95      * and removing them from the queue when they're obsolete.
     96      */
     97     // Android-added: @ReachabilitySensitive
     98     // Otherwise the finalizer may cancel the Timer in the middle of a
     99     // sched() call.
    100     @ReachabilitySensitive
    101     private final TaskQueue queue = new TaskQueue();
    102 
    103     /**
    104      * The timer thread.
    105      */
    106     // Android-added: @ReachabilitySensitive
    107     @ReachabilitySensitive
    108     private final TimerThread thread = new TimerThread(queue);
    109 
    110     /**
    111      * This object causes the timer's task execution thread to exit
    112      * gracefully when there are no live references to the Timer object and no
    113      * tasks in the timer queue.  It is used in preference to a finalizer on
    114      * Timer as such a finalizer would be susceptible to a subclass's
    115      * finalizer forgetting to call it.
    116      */
    117     private final Object threadReaper = new Object() {
    118         protected void finalize() throws Throwable {
    119             synchronized(queue) {
    120                 thread.newTasksMayBeScheduled = false;
    121                 queue.notify(); // In case queue is empty.
    122             }
    123         }
    124     };
    125 
    126     /**
    127      * This ID is used to generate thread names.
    128      */
    129     private final static AtomicInteger nextSerialNumber = new AtomicInteger(0);
    130     private static int serialNumber() {
    131         return nextSerialNumber.getAndIncrement();
    132     }
    133 
    134     /**
    135      * Creates a new timer.  The associated thread does <i>not</i>
    136      * {@linkplain Thread#setDaemon run as a daemon}.
    137      */
    138     public Timer() {
    139         this("Timer-" + serialNumber());
    140     }
    141 
    142     /**
    143      * Creates a new timer whose associated thread may be specified to
    144      * {@linkplain Thread#setDaemon run as a daemon}.
    145      * A daemon thread is called for if the timer will be used to
    146      * schedule repeating "maintenance activities", which must be
    147      * performed as long as the application is running, but should not
    148      * prolong the lifetime of the application.
    149      *
    150      * @param isDaemon true if the associated thread should run as a daemon.
    151      */
    152     public Timer(boolean isDaemon) {
    153         this("Timer-" + serialNumber(), isDaemon);
    154     }
    155 
    156     /**
    157      * Creates a new timer whose associated thread has the specified name.
    158      * The associated thread does <i>not</i>
    159      * {@linkplain Thread#setDaemon run as a daemon}.
    160      *
    161      * @param name the name of the associated thread
    162      * @throws NullPointerException if {@code name} is null
    163      * @since 1.5
    164      */
    165     public Timer(String name) {
    166         thread.setName(name);
    167         thread.start();
    168     }
    169 
    170     /**
    171      * Creates a new timer whose associated thread has the specified name,
    172      * and may be specified to
    173      * {@linkplain Thread#setDaemon run as a daemon}.
    174      *
    175      * @param name the name of the associated thread
    176      * @param isDaemon true if the associated thread should run as a daemon
    177      * @throws NullPointerException if {@code name} is null
    178      * @since 1.5
    179      */
    180     public Timer(String name, boolean isDaemon) {
    181         thread.setName(name);
    182         thread.setDaemon(isDaemon);
    183         thread.start();
    184     }
    185 
    186     /**
    187      * Schedules the specified task for execution after the specified delay.
    188      *
    189      * @param task  task to be scheduled.
    190      * @param delay delay in milliseconds before task is to be executed.
    191      * @throws IllegalArgumentException if <tt>delay</tt> is negative, or
    192      *         <tt>delay + System.currentTimeMillis()</tt> is negative.
    193      * @throws IllegalStateException if task was already scheduled or
    194      *         cancelled, timer was cancelled, or timer thread terminated.
    195      * @throws NullPointerException if {@code task} is null
    196      */
    197     public void schedule(TimerTask task, long delay) {
    198         if (delay < 0)
    199             throw new IllegalArgumentException("Negative delay.");
    200         sched(task, System.currentTimeMillis()+delay, 0);
    201     }
    202 
    203     /**
    204      * Schedules the specified task for execution at the specified time.  If
    205      * the time is in the past, the task is scheduled for immediate execution.
    206      *
    207      * @param task task to be scheduled.
    208      * @param time time at which task is to be executed.
    209      * @throws IllegalArgumentException if <tt>time.getTime()</tt> is negative.
    210      * @throws IllegalStateException if task was already scheduled or
    211      *         cancelled, timer was cancelled, or timer thread terminated.
    212      * @throws NullPointerException if {@code task} or {@code time} is null
    213      */
    214     public void schedule(TimerTask task, Date time) {
    215         sched(task, time.getTime(), 0);
    216     }
    217 
    218     /**
    219      * Schedules the specified task for repeated <i>fixed-delay execution</i>,
    220      * beginning after the specified delay.  Subsequent executions take place
    221      * at approximately regular intervals separated by the specified period.
    222      *
    223      * <p>In fixed-delay execution, each execution is scheduled relative to
    224      * the actual execution time of the previous execution.  If an execution
    225      * is delayed for any reason (such as garbage collection or other
    226      * background activity), subsequent executions will be delayed as well.
    227      * In the long run, the frequency of execution will generally be slightly
    228      * lower than the reciprocal of the specified period (assuming the system
    229      * clock underlying <tt>Object.wait(long)</tt> is accurate).
    230      *
    231      * <p>Fixed-delay execution is appropriate for recurring activities
    232      * that require "smoothness."  In other words, it is appropriate for
    233      * activities where it is more important to keep the frequency accurate
    234      * in the short run than in the long run.  This includes most animation
    235      * tasks, such as blinking a cursor at regular intervals.  It also includes
    236      * tasks wherein regular activity is performed in response to human
    237      * input, such as automatically repeating a character as long as a key
    238      * is held down.
    239      *
    240      * @param task   task to be scheduled.
    241      * @param delay  delay in milliseconds before task is to be executed.
    242      * @param period time in milliseconds between successive task executions.
    243      * @throws IllegalArgumentException if {@code delay < 0}, or
    244      *         {@code delay + System.currentTimeMillis() < 0}, or
    245      *         {@code period <= 0}
    246      * @throws IllegalStateException if task was already scheduled or
    247      *         cancelled, timer was cancelled, or timer thread terminated.
    248      * @throws NullPointerException if {@code task} is null
    249      */
    250     public void schedule(TimerTask task, long delay, long period) {
    251         if (delay < 0)
    252             throw new IllegalArgumentException("Negative delay.");
    253         if (period <= 0)
    254             throw new IllegalArgumentException("Non-positive period.");
    255         sched(task, System.currentTimeMillis()+delay, -period);
    256     }
    257 
    258     /**
    259      * Schedules the specified task for repeated <i>fixed-delay execution</i>,
    260      * beginning at the specified time. Subsequent executions take place at
    261      * approximately regular intervals, separated by the specified period.
    262      *
    263      * <p>In fixed-delay execution, each execution is scheduled relative to
    264      * the actual execution time of the previous execution.  If an execution
    265      * is delayed for any reason (such as garbage collection or other
    266      * background activity), subsequent executions will be delayed as well.
    267      * In the long run, the frequency of execution will generally be slightly
    268      * lower than the reciprocal of the specified period (assuming the system
    269      * clock underlying <tt>Object.wait(long)</tt> is accurate).  As a
    270      * consequence of the above, if the scheduled first time is in the past,
    271      * it is scheduled for immediate execution.
    272      *
    273      * <p>Fixed-delay execution is appropriate for recurring activities
    274      * that require "smoothness."  In other words, it is appropriate for
    275      * activities where it is more important to keep the frequency accurate
    276      * in the short run than in the long run.  This includes most animation
    277      * tasks, such as blinking a cursor at regular intervals.  It also includes
    278      * tasks wherein regular activity is performed in response to human
    279      * input, such as automatically repeating a character as long as a key
    280      * is held down.
    281      *
    282      * @param task   task to be scheduled.
    283      * @param firstTime First time at which task is to be executed.
    284      * @param period time in milliseconds between successive task executions.
    285      * @throws IllegalArgumentException if {@code firstTime.getTime() < 0}, or
    286      *         {@code period <= 0}
    287      * @throws IllegalStateException if task was already scheduled or
    288      *         cancelled, timer was cancelled, or timer thread terminated.
    289      * @throws NullPointerException if {@code task} or {@code firstTime} is null
    290      */
    291     public void schedule(TimerTask task, Date firstTime, long period) {
    292         if (period <= 0)
    293             throw new IllegalArgumentException("Non-positive period.");
    294         sched(task, firstTime.getTime(), -period);
    295     }
    296 
    297     /**
    298      * Schedules the specified task for repeated <i>fixed-rate execution</i>,
    299      * beginning after the specified delay.  Subsequent executions take place
    300      * at approximately regular intervals, separated by the specified period.
    301      *
    302      * <p>In fixed-rate execution, each execution is scheduled relative to the
    303      * scheduled execution time of the initial execution.  If an execution is
    304      * delayed for any reason (such as garbage collection or other background
    305      * activity), two or more executions will occur in rapid succession to
    306      * "catch up."  In the long run, the frequency of execution will be
    307      * exactly the reciprocal of the specified period (assuming the system
    308      * clock underlying <tt>Object.wait(long)</tt> is accurate).
    309      *
    310      * <p>Fixed-rate execution is appropriate for recurring activities that
    311      * are sensitive to <i>absolute</i> time, such as ringing a chime every
    312      * hour on the hour, or running scheduled maintenance every day at a
    313      * particular time.  It is also appropriate for recurring activities
    314      * where the total time to perform a fixed number of executions is
    315      * important, such as a countdown timer that ticks once every second for
    316      * ten seconds.  Finally, fixed-rate execution is appropriate for
    317      * scheduling multiple repeating timer tasks that must remain synchronized
    318      * with respect to one another.
    319      *
    320      * @param task   task to be scheduled.
    321      * @param delay  delay in milliseconds before task is to be executed.
    322      * @param period time in milliseconds between successive task executions.
    323      * @throws IllegalArgumentException if {@code delay < 0}, or
    324      *         {@code delay + System.currentTimeMillis() < 0}, or
    325      *         {@code period <= 0}
    326      * @throws IllegalStateException if task was already scheduled or
    327      *         cancelled, timer was cancelled, or timer thread terminated.
    328      * @throws NullPointerException if {@code task} is null
    329      */
    330     public void scheduleAtFixedRate(TimerTask task, long delay, long period) {
    331         if (delay < 0)
    332             throw new IllegalArgumentException("Negative delay.");
    333         if (period <= 0)
    334             throw new IllegalArgumentException("Non-positive period.");
    335         sched(task, System.currentTimeMillis()+delay, period);
    336     }
    337 
    338     /**
    339      * Schedules the specified task for repeated <i>fixed-rate execution</i>,
    340      * beginning at the specified time. Subsequent executions take place at
    341      * approximately regular intervals, separated by the specified period.
    342      *
    343      * <p>In fixed-rate execution, each execution is scheduled relative to the
    344      * scheduled execution time of the initial execution.  If an execution is
    345      * delayed for any reason (such as garbage collection or other background
    346      * activity), two or more executions will occur in rapid succession to
    347      * "catch up."  In the long run, the frequency of execution will be
    348      * exactly the reciprocal of the specified period (assuming the system
    349      * clock underlying <tt>Object.wait(long)</tt> is accurate).  As a
    350      * consequence of the above, if the scheduled first time is in the past,
    351      * then any "missed" executions will be scheduled for immediate "catch up"
    352      * execution.
    353      *
    354      * <p>Fixed-rate execution is appropriate for recurring activities that
    355      * are sensitive to <i>absolute</i> time, such as ringing a chime every
    356      * hour on the hour, or running scheduled maintenance every day at a
    357      * particular time.  It is also appropriate for recurring activities
    358      * where the total time to perform a fixed number of executions is
    359      * important, such as a countdown timer that ticks once every second for
    360      * ten seconds.  Finally, fixed-rate execution is appropriate for
    361      * scheduling multiple repeating timer tasks that must remain synchronized
    362      * with respect to one another.
    363      *
    364      * @param task   task to be scheduled.
    365      * @param firstTime First time at which task is to be executed.
    366      * @param period time in milliseconds between successive task executions.
    367      * @throws IllegalArgumentException if {@code firstTime.getTime() < 0} or
    368      *         {@code period <= 0}
    369      * @throws IllegalStateException if task was already scheduled or
    370      *         cancelled, timer was cancelled, or timer thread terminated.
    371      * @throws NullPointerException if {@code task} or {@code firstTime} is null
    372      */
    373     public void scheduleAtFixedRate(TimerTask task, Date firstTime,
    374                                     long period) {
    375         if (period <= 0)
    376             throw new IllegalArgumentException("Non-positive period.");
    377         sched(task, firstTime.getTime(), period);
    378     }
    379 
    380     /**
    381      * Schedule the specified timer task for execution at the specified
    382      * time with the specified period, in milliseconds.  If period is
    383      * positive, the task is scheduled for repeated execution; if period is
    384      * zero, the task is scheduled for one-time execution. Time is specified
    385      * in Date.getTime() format.  This method checks timer state, task state,
    386      * and initial execution time, but not period.
    387      *
    388      * @throws IllegalArgumentException if <tt>time</tt> is negative.
    389      * @throws IllegalStateException if task was already scheduled or
    390      *         cancelled, timer was cancelled, or timer thread terminated.
    391      * @throws NullPointerException if {@code task} is null
    392      */
    393     private void sched(TimerTask task, long time, long period) {
    394         if (time < 0)
    395             throw new IllegalArgumentException("Illegal execution time.");
    396 
    397         // Constrain value of period sufficiently to prevent numeric
    398         // overflow while still being effectively infinitely large.
    399         if (Math.abs(period) > (Long.MAX_VALUE >> 1))
    400             period >>= 1;
    401 
    402         synchronized(queue) {
    403             if (!thread.newTasksMayBeScheduled)
    404                 throw new IllegalStateException("Timer already cancelled.");
    405 
    406             synchronized(task.lock) {
    407                 if (task.state != TimerTask.VIRGIN)
    408                     throw new IllegalStateException(
    409                         "Task already scheduled or cancelled");
    410                 task.nextExecutionTime = time;
    411                 task.period = period;
    412                 task.state = TimerTask.SCHEDULED;
    413             }
    414 
    415             queue.add(task);
    416             if (queue.getMin() == task)
    417                 queue.notify();
    418         }
    419     }
    420 
    421     /**
    422      * Terminates this timer, discarding any currently scheduled tasks.
    423      * Does not interfere with a currently executing task (if it exists).
    424      * Once a timer has been terminated, its execution thread terminates
    425      * gracefully, and no more tasks may be scheduled on it.
    426      *
    427      * <p>Note that calling this method from within the run method of a
    428      * timer task that was invoked by this timer absolutely guarantees that
    429      * the ongoing task execution is the last task execution that will ever
    430      * be performed by this timer.
    431      *
    432      * <p>This method may be called repeatedly; the second and subsequent
    433      * calls have no effect.
    434      */
    435     public void cancel() {
    436         synchronized(queue) {
    437             thread.newTasksMayBeScheduled = false;
    438             queue.clear();
    439             queue.notify();  // In case queue was already empty.
    440         }
    441     }
    442 
    443     /**
    444      * Removes all cancelled tasks from this timer's task queue.  <i>Calling
    445      * this method has no effect on the behavior of the timer</i>, but
    446      * eliminates the references to the cancelled tasks from the queue.
    447      * If there are no external references to these tasks, they become
    448      * eligible for garbage collection.
    449      *
    450      * <p>Most programs will have no need to call this method.
    451      * It is designed for use by the rare application that cancels a large
    452      * number of tasks.  Calling this method trades time for space: the
    453      * runtime of the method may be proportional to n + c log n, where n
    454      * is the number of tasks in the queue and c is the number of cancelled
    455      * tasks.
    456      *
    457      * <p>Note that it is permissible to call this method from within a
    458      * a task scheduled on this timer.
    459      *
    460      * @return the number of tasks removed from the queue.
    461      * @since 1.5
    462      */
    463      public int purge() {
    464          int result = 0;
    465 
    466          synchronized(queue) {
    467              for (int i = queue.size(); i > 0; i--) {
    468                  if (queue.get(i).state == TimerTask.CANCELLED) {
    469                      queue.quickRemove(i);
    470                      result++;
    471                  }
    472              }
    473 
    474              if (result != 0)
    475                  queue.heapify();
    476          }
    477 
    478          return result;
    479      }
    480 }
    481 
    482 /**
    483  * This "helper class" implements the timer's task execution thread, which
    484  * waits for tasks on the timer queue, executions them when they fire,
    485  * reschedules repeating tasks, and removes cancelled tasks and spent
    486  * non-repeating tasks from the queue.
    487  */
    488 class TimerThread extends Thread {
    489     /**
    490      * This flag is set to false by the reaper to inform us that there
    491      * are no more live references to our Timer object.  Once this flag
    492      * is true and there are no more tasks in our queue, there is no
    493      * work left for us to do, so we terminate gracefully.  Note that
    494      * this field is protected by queue's monitor!
    495      */
    496     boolean newTasksMayBeScheduled = true;
    497 
    498     /**
    499      * Our Timer's queue.  We store this reference in preference to
    500      * a reference to the Timer so the reference graph remains acyclic.
    501      * Otherwise, the Timer would never be garbage-collected and this
    502      * thread would never go away.
    503      */
    504     private TaskQueue queue;
    505 
    506     TimerThread(TaskQueue queue) {
    507         this.queue = queue;
    508     }
    509 
    510     public void run() {
    511         try {
    512             mainLoop();
    513         } finally {
    514             // Someone killed this Thread, behave as if Timer cancelled
    515             synchronized(queue) {
    516                 newTasksMayBeScheduled = false;
    517                 queue.clear();  // Eliminate obsolete references
    518             }
    519         }
    520     }
    521 
    522     /**
    523      * The main timer loop.  (See class comment.)
    524      */
    525     private void mainLoop() {
    526         while (true) {
    527             try {
    528                 TimerTask task;
    529                 boolean taskFired;
    530                 synchronized(queue) {
    531                     // Wait for queue to become non-empty
    532                     while (queue.isEmpty() && newTasksMayBeScheduled)
    533                         queue.wait();
    534                     if (queue.isEmpty())
    535                         break; // Queue is empty and will forever remain; die
    536 
    537                     // Queue nonempty; look at first evt and do the right thing
    538                     long currentTime, executionTime;
    539                     task = queue.getMin();
    540                     synchronized(task.lock) {
    541                         if (task.state == TimerTask.CANCELLED) {
    542                             queue.removeMin();
    543                             continue;  // No action required, poll queue again
    544                         }
    545                         currentTime = System.currentTimeMillis();
    546                         executionTime = task.nextExecutionTime;
    547                         if (taskFired = (executionTime<=currentTime)) {
    548                             if (task.period == 0) { // Non-repeating, remove
    549                                 queue.removeMin();
    550                                 task.state = TimerTask.EXECUTED;
    551                             } else { // Repeating task, reschedule
    552                                 queue.rescheduleMin(
    553                                   task.period<0 ? currentTime   - task.period
    554                                                 : executionTime + task.period);
    555                             }
    556                         }
    557                     }
    558                     if (!taskFired) // Task hasn't yet fired; wait
    559                         queue.wait(executionTime - currentTime);
    560                 }
    561                 if (taskFired)  // Task fired; run it, holding no locks
    562                     task.run();
    563             } catch(InterruptedException e) {
    564             }
    565         }
    566     }
    567 }
    568 
    569 /**
    570  * This class represents a timer task queue: a priority queue of TimerTasks,
    571  * ordered on nextExecutionTime.  Each Timer object has one of these, which it
    572  * shares with its TimerThread.  Internally this class uses a heap, which
    573  * offers log(n) performance for the add, removeMin and rescheduleMin
    574  * operations, and constant time performance for the getMin operation.
    575  */
    576 class TaskQueue {
    577     /**
    578      * Priority queue represented as a balanced binary heap: the two children
    579      * of queue[n] are queue[2*n] and queue[2*n+1].  The priority queue is
    580      * ordered on the nextExecutionTime field: The TimerTask with the lowest
    581      * nextExecutionTime is in queue[1] (assuming the queue is nonempty).  For
    582      * each node n in the heap, and each descendant of n, d,
    583      * n.nextExecutionTime <= d.nextExecutionTime.
    584      */
    585     private TimerTask[] queue = new TimerTask[128];
    586 
    587     /**
    588      * The number of tasks in the priority queue.  (The tasks are stored in
    589      * queue[1] up to queue[size]).
    590      */
    591     private int size = 0;
    592 
    593     /**
    594      * Returns the number of tasks currently on the queue.
    595      */
    596     int size() {
    597         return size;
    598     }
    599 
    600     /**
    601      * Adds a new task to the priority queue.
    602      */
    603     void add(TimerTask task) {
    604         // Grow backing store if necessary
    605         if (size + 1 == queue.length)
    606             queue = Arrays.copyOf(queue, 2*queue.length);
    607 
    608         queue[++size] = task;
    609         fixUp(size);
    610     }
    611 
    612     /**
    613      * Return the "head task" of the priority queue.  (The head task is an
    614      * task with the lowest nextExecutionTime.)
    615      */
    616     TimerTask getMin() {
    617         return queue[1];
    618     }
    619 
    620     /**
    621      * Return the ith task in the priority queue, where i ranges from 1 (the
    622      * head task, which is returned by getMin) to the number of tasks on the
    623      * queue, inclusive.
    624      */
    625     TimerTask get(int i) {
    626         return queue[i];
    627     }
    628 
    629     /**
    630      * Remove the head task from the priority queue.
    631      */
    632     void removeMin() {
    633         queue[1] = queue[size];
    634         queue[size--] = null;  // Drop extra reference to prevent memory leak
    635         fixDown(1);
    636     }
    637 
    638     /**
    639      * Removes the ith element from queue without regard for maintaining
    640      * the heap invariant.  Recall that queue is one-based, so
    641      * 1 <= i <= size.
    642      */
    643     void quickRemove(int i) {
    644         assert i <= size;
    645 
    646         queue[i] = queue[size];
    647         queue[size--] = null;  // Drop extra ref to prevent memory leak
    648     }
    649 
    650     /**
    651      * Sets the nextExecutionTime associated with the head task to the
    652      * specified value, and adjusts priority queue accordingly.
    653      */
    654     void rescheduleMin(long newTime) {
    655         queue[1].nextExecutionTime = newTime;
    656         fixDown(1);
    657     }
    658 
    659     /**
    660      * Returns true if the priority queue contains no elements.
    661      */
    662     boolean isEmpty() {
    663         return size==0;
    664     }
    665 
    666     /**
    667      * Removes all elements from the priority queue.
    668      */
    669     void clear() {
    670         // Null out task references to prevent memory leak
    671         for (int i=1; i<=size; i++)
    672             queue[i] = null;
    673 
    674         size = 0;
    675     }
    676 
    677     /**
    678      * Establishes the heap invariant (described above) assuming the heap
    679      * satisfies the invariant except possibly for the leaf-node indexed by k
    680      * (which may have a nextExecutionTime less than its parent's).
    681      *
    682      * This method functions by "promoting" queue[k] up the hierarchy
    683      * (by swapping it with its parent) repeatedly until queue[k]'s
    684      * nextExecutionTime is greater than or equal to that of its parent.
    685      */
    686     private void fixUp(int k) {
    687         while (k > 1) {
    688             int j = k >> 1;
    689             if (queue[j].nextExecutionTime <= queue[k].nextExecutionTime)
    690                 break;
    691             TimerTask tmp = queue[j];  queue[j] = queue[k]; queue[k] = tmp;
    692             k = j;
    693         }
    694     }
    695 
    696     /**
    697      * Establishes the heap invariant (described above) in the subtree
    698      * rooted at k, which is assumed to satisfy the heap invariant except
    699      * possibly for node k itself (which may have a nextExecutionTime greater
    700      * than its children's).
    701      *
    702      * This method functions by "demoting" queue[k] down the hierarchy
    703      * (by swapping it with its smaller child) repeatedly until queue[k]'s
    704      * nextExecutionTime is less than or equal to those of its children.
    705      */
    706     private void fixDown(int k) {
    707         int j;
    708         while ((j = k << 1) <= size && j > 0) {
    709             if (j < size &&
    710                 queue[j].nextExecutionTime > queue[j+1].nextExecutionTime)
    711                 j++; // j indexes smallest kid
    712             if (queue[k].nextExecutionTime <= queue[j].nextExecutionTime)
    713                 break;
    714             TimerTask tmp = queue[j];  queue[j] = queue[k]; queue[k] = tmp;
    715             k = j;
    716         }
    717     }
    718 
    719     /**
    720      * Establishes the heap invariant (described above) in the entire tree,
    721      * assuming nothing about the order of the elements prior to the call.
    722      */
    723     void heapify() {
    724         for (int i = size/2; i >= 1; i--)
    725             fixDown(i);
    726     }
    727 }
    728