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