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