jtulach@1405: /* jtulach@1405: * Copyright (c) 1999, 2008, Oracle and/or its affiliates. All rights reserved. jtulach@1405: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. jtulach@1405: * jtulach@1405: * This code is free software; you can redistribute it and/or modify it jtulach@1405: * under the terms of the GNU General Public License version 2 only, as jtulach@1405: * published by the Free Software Foundation. Oracle designates this jtulach@1405: * particular file as subject to the "Classpath" exception as provided jtulach@1405: * by Oracle in the LICENSE file that accompanied this code. jtulach@1405: * jtulach@1405: * This code is distributed in the hope that it will be useful, but WITHOUT jtulach@1405: * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or jtulach@1405: * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License jtulach@1405: * version 2 for more details (a copy is included in the LICENSE file that jtulach@1405: * accompanied this code). jtulach@1405: * jtulach@1405: * You should have received a copy of the GNU General Public License version jtulach@1405: * 2 along with this work; if not, write to the Free Software Foundation, jtulach@1405: * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. jtulach@1405: * jtulach@1405: * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA jtulach@1405: * or visit www.oracle.com if you need additional information or have any jtulach@1405: * questions. jtulach@1405: */ jtulach@1405: jtulach@1405: package java.util; jtulach@1405: import java.util.Date; jtulach@1405: import java.util.concurrent.atomic.AtomicInteger; jtulach@1405: jtulach@1405: /** jtulach@1405: * A facility for threads to schedule tasks for future execution in a jtulach@1405: * background thread. Tasks may be scheduled for one-time execution, or for jtulach@1405: * repeated execution at regular intervals. jtulach@1405: * jtulach@1405: *

Corresponding to each Timer object is a single background jtulach@1405: * thread that is used to execute all of the timer's tasks, sequentially. jtulach@1405: * Timer tasks should complete quickly. If a timer task takes excessive time jtulach@1405: * to complete, it "hogs" the timer's task execution thread. This can, in jtulach@1405: * turn, delay the execution of subsequent tasks, which may "bunch up" and jtulach@1405: * execute in rapid succession when (and if) the offending task finally jtulach@1405: * completes. jtulach@1405: * jtulach@1405: *

After the last live reference to a Timer object goes away jtulach@1405: * and all outstanding tasks have completed execution, the timer's task jtulach@1405: * execution thread terminates gracefully (and becomes subject to garbage jtulach@1405: * collection). However, this can take arbitrarily long to occur. By jtulach@1405: * default, the task execution thread does not run as a daemon thread, jtulach@1405: * so it is capable of keeping an application from terminating. If a caller jtulach@1405: * wants to terminate a timer's task execution thread rapidly, the caller jtulach@1405: * should invoke the timer's cancel method. jtulach@1405: * jtulach@1405: *

If the timer's task execution thread terminates unexpectedly, for jtulach@1405: * example, because its stop method is invoked, any further jtulach@1405: * attempt to schedule a task on the timer will result in an jtulach@1405: * IllegalStateException, as if the timer's cancel jtulach@1405: * method had been invoked. jtulach@1405: * jtulach@1405: *

This class is thread-safe: multiple threads can share a single jtulach@1405: * Timer object without the need for external synchronization. jtulach@1405: * jtulach@1405: *

This class does not offer real-time guarantees: it schedules jtulach@1405: * tasks using the Object.wait(long) method. jtulach@1405: * jtulach@1405: *

Java 5.0 introduced the {@code java.util.concurrent} package and jtulach@1405: * one of the concurrency utilities therein is the {@link jtulach@1405: * java.util.concurrent.ScheduledThreadPoolExecutor jtulach@1405: * ScheduledThreadPoolExecutor} which is a thread pool for repeatedly jtulach@1405: * executing tasks at a given rate or delay. It is effectively a more jtulach@1405: * versatile replacement for the {@code Timer}/{@code TimerTask} jtulach@1405: * combination, as it allows multiple service threads, accepts various jtulach@1405: * time units, and doesn't require subclassing {@code TimerTask} (just jtulach@1405: * implement {@code Runnable}). Configuring {@code jtulach@1405: * ScheduledThreadPoolExecutor} with one thread makes it equivalent to jtulach@1405: * {@code Timer}. jtulach@1405: * jtulach@1405: *

Implementation note: This class scales to large numbers of concurrently jtulach@1405: * scheduled tasks (thousands should present no problem). Internally, jtulach@1405: * it uses a binary heap to represent its task queue, so the cost to schedule jtulach@1405: * a task is O(log n), where n is the number of concurrently scheduled tasks. jtulach@1405: * jtulach@1405: *

Implementation note: All constructors start a timer thread. jtulach@1405: * jtulach@1405: * @author Josh Bloch jtulach@1405: * @see TimerTask jtulach@1405: * @see Object#wait(long) jtulach@1405: * @since 1.3 jtulach@1405: */ jtulach@1405: jtulach@1405: public class Timer { jtulach@1405: /** jtulach@1405: * The timer task queue. This data structure is shared with the timer jtulach@1405: * thread. The timer produces tasks, via its various schedule calls, jtulach@1405: * and the timer thread consumes, executing timer tasks as appropriate, jtulach@1405: * and removing them from the queue when they're obsolete. jtulach@1405: */ jtulach@1405: private final TaskQueue queue = new TaskQueue(); jtulach@1405: jtulach@1405: /** jtulach@1405: * The timer thread. jtulach@1405: */ jtulach@1405: private final TimerThread thread = new TimerThread(queue); jtulach@1405: jtulach@1405: /** jtulach@1405: * This object causes the timer's task execution thread to exit jtulach@1405: * gracefully when there are no live references to the Timer object and no jtulach@1405: * tasks in the timer queue. It is used in preference to a finalizer on jtulach@1405: * Timer as such a finalizer would be susceptible to a subclass's jtulach@1405: * finalizer forgetting to call it. jtulach@1405: */ jtulach@1405: private final Object threadReaper = new Object() { jtulach@1405: protected void finalize() throws Throwable { jtulach@1405: synchronized(queue) { jtulach@1405: thread.newTasksMayBeScheduled = false; jtulach@1405: queue.notify(); // In case queue is empty. jtulach@1405: } jtulach@1405: } jtulach@1405: }; jtulach@1405: jtulach@1405: /** jtulach@1405: * This ID is used to generate thread names. jtulach@1405: */ jtulach@1405: private final static AtomicInteger nextSerialNumber = new AtomicInteger(0); jtulach@1405: private static int serialNumber() { jtulach@1405: return nextSerialNumber.getAndIncrement(); jtulach@1405: } jtulach@1405: jtulach@1405: /** jtulach@1405: * Creates a new timer. The associated thread does not jtulach@1405: * {@linkplain Thread#setDaemon run as a daemon}. jtulach@1405: */ jtulach@1405: public Timer() { jtulach@1405: this("Timer-" + serialNumber()); jtulach@1405: } jtulach@1405: jtulach@1405: /** jtulach@1405: * Creates a new timer whose associated thread may be specified to jtulach@1405: * {@linkplain Thread#setDaemon run as a daemon}. jtulach@1405: * A daemon thread is called for if the timer will be used to jtulach@1405: * schedule repeating "maintenance activities", which must be jtulach@1405: * performed as long as the application is running, but should not jtulach@1405: * prolong the lifetime of the application. jtulach@1405: * jtulach@1405: * @param isDaemon true if the associated thread should run as a daemon. jtulach@1405: */ jtulach@1405: public Timer(boolean isDaemon) { jtulach@1405: this("Timer-" + serialNumber(), isDaemon); jtulach@1405: } jtulach@1405: jtulach@1405: /** jtulach@1405: * Creates a new timer whose associated thread has the specified name. jtulach@1405: * The associated thread does not jtulach@1405: * {@linkplain Thread#setDaemon run as a daemon}. jtulach@1405: * jtulach@1405: * @param name the name of the associated thread jtulach@1405: * @throws NullPointerException if {@code name} is null jtulach@1405: * @since 1.5 jtulach@1405: */ jtulach@1405: public Timer(String name) { jtulach@1405: thread.setName(name); jtulach@1405: thread.start(); jtulach@1405: } jtulach@1405: jtulach@1405: /** jtulach@1405: * Creates a new timer whose associated thread has the specified name, jtulach@1405: * and may be specified to jtulach@1405: * {@linkplain Thread#setDaemon run as a daemon}. jtulach@1405: * jtulach@1405: * @param name the name of the associated thread jtulach@1405: * @param isDaemon true if the associated thread should run as a daemon jtulach@1405: * @throws NullPointerException if {@code name} is null jtulach@1405: * @since 1.5 jtulach@1405: */ jtulach@1405: public Timer(String name, boolean isDaemon) { jtulach@1405: thread.setName(name); jtulach@1405: thread.setDaemon(isDaemon); jtulach@1405: thread.start(); jtulach@1405: } jtulach@1405: jtulach@1405: /** jtulach@1405: * Schedules the specified task for execution after the specified delay. jtulach@1405: * jtulach@1405: * @param task task to be scheduled. jtulach@1405: * @param delay delay in milliseconds before task is to be executed. jtulach@1405: * @throws IllegalArgumentException if delay is negative, or jtulach@1405: * delay + System.currentTimeMillis() is negative. jtulach@1405: * @throws IllegalStateException if task was already scheduled or jtulach@1405: * cancelled, timer was cancelled, or timer thread terminated. jtulach@1405: * @throws NullPointerException if {@code task} is null jtulach@1405: */ jtulach@1405: public void schedule(TimerTask task, long delay) { jtulach@1405: if (delay < 0) jtulach@1405: throw new IllegalArgumentException("Negative delay."); jtulach@1405: sched(task, System.currentTimeMillis()+delay, 0); jtulach@1405: } jtulach@1405: jtulach@1405: /** jtulach@1405: * Schedules the specified task for execution at the specified time. If jtulach@1405: * the time is in the past, the task is scheduled for immediate execution. jtulach@1405: * jtulach@1405: * @param task task to be scheduled. jtulach@1405: * @param time time at which task is to be executed. jtulach@1405: * @throws IllegalArgumentException if time.getTime() is negative. jtulach@1405: * @throws IllegalStateException if task was already scheduled or jtulach@1405: * cancelled, timer was cancelled, or timer thread terminated. jtulach@1405: * @throws NullPointerException if {@code task} or {@code time} is null jtulach@1405: */ jtulach@1405: public void schedule(TimerTask task, Date time) { jtulach@1405: sched(task, time.getTime(), 0); jtulach@1405: } jtulach@1405: jtulach@1405: /** jtulach@1405: * Schedules the specified task for repeated fixed-delay execution, jtulach@1405: * beginning after the specified delay. Subsequent executions take place jtulach@1405: * at approximately regular intervals separated by the specified period. jtulach@1405: * jtulach@1405: *

In fixed-delay execution, each execution is scheduled relative to jtulach@1405: * the actual execution time of the previous execution. If an execution jtulach@1405: * is delayed for any reason (such as garbage collection or other jtulach@1405: * background activity), subsequent executions will be delayed as well. jtulach@1405: * In the long run, the frequency of execution will generally be slightly jtulach@1405: * lower than the reciprocal of the specified period (assuming the system jtulach@1405: * clock underlying Object.wait(long) is accurate). jtulach@1405: * jtulach@1405: *

Fixed-delay execution is appropriate for recurring activities jtulach@1405: * that require "smoothness." In other words, it is appropriate for jtulach@1405: * activities where it is more important to keep the frequency accurate jtulach@1405: * in the short run than in the long run. This includes most animation jtulach@1405: * tasks, such as blinking a cursor at regular intervals. It also includes jtulach@1405: * tasks wherein regular activity is performed in response to human jtulach@1405: * input, such as automatically repeating a character as long as a key jtulach@1405: * is held down. jtulach@1405: * jtulach@1405: * @param task task to be scheduled. jtulach@1405: * @param delay delay in milliseconds before task is to be executed. jtulach@1405: * @param period time in milliseconds between successive task executions. jtulach@1405: * @throws IllegalArgumentException if {@code delay < 0}, or jtulach@1405: * {@code delay + System.currentTimeMillis() < 0}, or jtulach@1405: * {@code period <= 0} jtulach@1405: * @throws IllegalStateException if task was already scheduled or jtulach@1405: * cancelled, timer was cancelled, or timer thread terminated. jtulach@1405: * @throws NullPointerException if {@code task} is null jtulach@1405: */ jtulach@1405: public void schedule(TimerTask task, long delay, long period) { jtulach@1405: if (delay < 0) jtulach@1405: throw new IllegalArgumentException("Negative delay."); jtulach@1405: if (period <= 0) jtulach@1405: throw new IllegalArgumentException("Non-positive period."); jtulach@1405: sched(task, System.currentTimeMillis()+delay, -period); jtulach@1405: } jtulach@1405: jtulach@1405: /** jtulach@1405: * Schedules the specified task for repeated fixed-delay execution, jtulach@1405: * beginning at the specified time. Subsequent executions take place at jtulach@1405: * approximately regular intervals, separated by the specified period. jtulach@1405: * jtulach@1405: *

In fixed-delay execution, each execution is scheduled relative to jtulach@1405: * the actual execution time of the previous execution. If an execution jtulach@1405: * is delayed for any reason (such as garbage collection or other jtulach@1405: * background activity), subsequent executions will be delayed as well. jtulach@1405: * In the long run, the frequency of execution will generally be slightly jtulach@1405: * lower than the reciprocal of the specified period (assuming the system jtulach@1405: * clock underlying Object.wait(long) is accurate). As a jtulach@1405: * consequence of the above, if the scheduled first time is in the past, jtulach@1405: * it is scheduled for immediate execution. jtulach@1405: * jtulach@1405: *

Fixed-delay execution is appropriate for recurring activities jtulach@1405: * that require "smoothness." In other words, it is appropriate for jtulach@1405: * activities where it is more important to keep the frequency accurate jtulach@1405: * in the short run than in the long run. This includes most animation jtulach@1405: * tasks, such as blinking a cursor at regular intervals. It also includes jtulach@1405: * tasks wherein regular activity is performed in response to human jtulach@1405: * input, such as automatically repeating a character as long as a key jtulach@1405: * is held down. jtulach@1405: * jtulach@1405: * @param task task to be scheduled. jtulach@1405: * @param firstTime First time at which task is to be executed. jtulach@1405: * @param period time in milliseconds between successive task executions. jtulach@1405: * @throws IllegalArgumentException if {@code firstTime.getTime() < 0}, or jtulach@1405: * {@code period <= 0} jtulach@1405: * @throws IllegalStateException if task was already scheduled or jtulach@1405: * cancelled, timer was cancelled, or timer thread terminated. jtulach@1405: * @throws NullPointerException if {@code task} or {@code firstTime} is null jtulach@1405: */ jtulach@1405: public void schedule(TimerTask task, Date firstTime, long period) { jtulach@1405: if (period <= 0) jtulach@1405: throw new IllegalArgumentException("Non-positive period."); jtulach@1405: sched(task, firstTime.getTime(), -period); jtulach@1405: } jtulach@1405: jtulach@1405: /** jtulach@1405: * Schedules the specified task for repeated fixed-rate execution, jtulach@1405: * beginning after the specified delay. Subsequent executions take place jtulach@1405: * at approximately regular intervals, separated by the specified period. jtulach@1405: * jtulach@1405: *

In fixed-rate execution, each execution is scheduled relative to the jtulach@1405: * scheduled execution time of the initial execution. If an execution is jtulach@1405: * delayed for any reason (such as garbage collection or other background jtulach@1405: * activity), two or more executions will occur in rapid succession to jtulach@1405: * "catch up." In the long run, the frequency of execution will be jtulach@1405: * exactly the reciprocal of the specified period (assuming the system jtulach@1405: * clock underlying Object.wait(long) is accurate). jtulach@1405: * jtulach@1405: *

Fixed-rate execution is appropriate for recurring activities that jtulach@1405: * are sensitive to absolute time, such as ringing a chime every jtulach@1405: * hour on the hour, or running scheduled maintenance every day at a jtulach@1405: * particular time. It is also appropriate for recurring activities jtulach@1405: * where the total time to perform a fixed number of executions is jtulach@1405: * important, such as a countdown timer that ticks once every second for jtulach@1405: * ten seconds. Finally, fixed-rate execution is appropriate for jtulach@1405: * scheduling multiple repeating timer tasks that must remain synchronized jtulach@1405: * with respect to one another. jtulach@1405: * jtulach@1405: * @param task task to be scheduled. jtulach@1405: * @param delay delay in milliseconds before task is to be executed. jtulach@1405: * @param period time in milliseconds between successive task executions. jtulach@1405: * @throws IllegalArgumentException if {@code delay < 0}, or jtulach@1405: * {@code delay + System.currentTimeMillis() < 0}, or jtulach@1405: * {@code period <= 0} jtulach@1405: * @throws IllegalStateException if task was already scheduled or jtulach@1405: * cancelled, timer was cancelled, or timer thread terminated. jtulach@1405: * @throws NullPointerException if {@code task} is null jtulach@1405: */ jtulach@1405: public void scheduleAtFixedRate(TimerTask task, long delay, long period) { jtulach@1405: if (delay < 0) jtulach@1405: throw new IllegalArgumentException("Negative delay."); jtulach@1405: if (period <= 0) jtulach@1405: throw new IllegalArgumentException("Non-positive period."); jtulach@1405: sched(task, System.currentTimeMillis()+delay, period); jtulach@1405: } jtulach@1405: jtulach@1405: /** jtulach@1405: * Schedules the specified task for repeated fixed-rate execution, jtulach@1405: * beginning at the specified time. Subsequent executions take place at jtulach@1405: * approximately regular intervals, separated by the specified period. jtulach@1405: * jtulach@1405: *

In fixed-rate execution, each execution is scheduled relative to the jtulach@1405: * scheduled execution time of the initial execution. If an execution is jtulach@1405: * delayed for any reason (such as garbage collection or other background jtulach@1405: * activity), two or more executions will occur in rapid succession to jtulach@1405: * "catch up." In the long run, the frequency of execution will be jtulach@1405: * exactly the reciprocal of the specified period (assuming the system jtulach@1405: * clock underlying Object.wait(long) is accurate). As a jtulach@1405: * consequence of the above, if the scheduled first time is in the past, jtulach@1405: * then any "missed" executions will be scheduled for immediate "catch up" jtulach@1405: * execution. jtulach@1405: * jtulach@1405: *

Fixed-rate execution is appropriate for recurring activities that jtulach@1405: * are sensitive to absolute time, such as ringing a chime every jtulach@1405: * hour on the hour, or running scheduled maintenance every day at a jtulach@1405: * particular time. It is also appropriate for recurring activities jtulach@1405: * where the total time to perform a fixed number of executions is jtulach@1405: * important, such as a countdown timer that ticks once every second for jtulach@1405: * ten seconds. Finally, fixed-rate execution is appropriate for jtulach@1405: * scheduling multiple repeating timer tasks that must remain synchronized jtulach@1405: * with respect to one another. jtulach@1405: * jtulach@1405: * @param task task to be scheduled. jtulach@1405: * @param firstTime First time at which task is to be executed. jtulach@1405: * @param period time in milliseconds between successive task executions. jtulach@1405: * @throws IllegalArgumentException if {@code firstTime.getTime() < 0} or jtulach@1405: * {@code period <= 0} jtulach@1405: * @throws IllegalStateException if task was already scheduled or jtulach@1405: * cancelled, timer was cancelled, or timer thread terminated. jtulach@1405: * @throws NullPointerException if {@code task} or {@code firstTime} is null jtulach@1405: */ jtulach@1405: public void scheduleAtFixedRate(TimerTask task, Date firstTime, jtulach@1405: long period) { jtulach@1405: if (period <= 0) jtulach@1405: throw new IllegalArgumentException("Non-positive period."); jtulach@1405: sched(task, firstTime.getTime(), period); jtulach@1405: } jtulach@1405: jtulach@1405: /** jtulach@1405: * Schedule the specified timer task for execution at the specified jtulach@1405: * time with the specified period, in milliseconds. If period is jtulach@1405: * positive, the task is scheduled for repeated execution; if period is jtulach@1405: * zero, the task is scheduled for one-time execution. Time is specified jtulach@1405: * in Date.getTime() format. This method checks timer state, task state, jtulach@1405: * and initial execution time, but not period. jtulach@1405: * jtulach@1405: * @throws IllegalArgumentException if time is negative. jtulach@1405: * @throws IllegalStateException if task was already scheduled or jtulach@1405: * cancelled, timer was cancelled, or timer thread terminated. jtulach@1405: * @throws NullPointerException if {@code task} is null jtulach@1405: */ jtulach@1405: private void sched(TimerTask task, long time, long period) { jtulach@1405: if (time < 0) jtulach@1405: throw new IllegalArgumentException("Illegal execution time."); jtulach@1405: jtulach@1405: // Constrain value of period sufficiently to prevent numeric jtulach@1405: // overflow while still being effectively infinitely large. jtulach@1405: if (Math.abs(period) > (Long.MAX_VALUE >> 1)) jtulach@1405: period >>= 1; jtulach@1405: jtulach@1405: synchronized(queue) { jtulach@1405: if (!thread.newTasksMayBeScheduled) jtulach@1405: throw new IllegalStateException("Timer already cancelled."); jtulach@1405: jtulach@1405: synchronized(task.lock) { jtulach@1405: if (task.state != TimerTask.VIRGIN) jtulach@1405: throw new IllegalStateException( jtulach@1405: "Task already scheduled or cancelled"); jtulach@1405: task.nextExecutionTime = time; jtulach@1405: task.period = period; jtulach@1405: task.state = TimerTask.SCHEDULED; jtulach@1405: } jtulach@1405: jtulach@1405: queue.add(task); jtulach@1405: if (queue.getMin() == task) jtulach@1405: queue.notify(); jtulach@1405: } jtulach@1405: } jtulach@1405: jtulach@1405: /** jtulach@1405: * Terminates this timer, discarding any currently scheduled tasks. jtulach@1405: * Does not interfere with a currently executing task (if it exists). jtulach@1405: * Once a timer has been terminated, its execution thread terminates jtulach@1405: * gracefully, and no more tasks may be scheduled on it. jtulach@1405: * jtulach@1405: *

Note that calling this method from within the run method of a jtulach@1405: * timer task that was invoked by this timer absolutely guarantees that jtulach@1405: * the ongoing task execution is the last task execution that will ever jtulach@1405: * be performed by this timer. jtulach@1405: * jtulach@1405: *

This method may be called repeatedly; the second and subsequent jtulach@1405: * calls have no effect. jtulach@1405: */ jtulach@1405: public void cancel() { jtulach@1405: synchronized(queue) { jtulach@1405: thread.newTasksMayBeScheduled = false; jtulach@1405: queue.clear(); jtulach@1405: queue.notify(); // In case queue was already empty. jtulach@1405: } jtulach@1405: } jtulach@1405: jtulach@1405: /** jtulach@1405: * Removes all cancelled tasks from this timer's task queue. Calling jtulach@1405: * this method has no effect on the behavior of the timer, but jtulach@1405: * eliminates the references to the cancelled tasks from the queue. jtulach@1405: * If there are no external references to these tasks, they become jtulach@1405: * eligible for garbage collection. jtulach@1405: * jtulach@1405: *

Most programs will have no need to call this method. jtulach@1405: * It is designed for use by the rare application that cancels a large jtulach@1405: * number of tasks. Calling this method trades time for space: the jtulach@1405: * runtime of the method may be proportional to n + c log n, where n jtulach@1405: * is the number of tasks in the queue and c is the number of cancelled jtulach@1405: * tasks. jtulach@1405: * jtulach@1405: *

Note that it is permissible to call this method from within a jtulach@1405: * a task scheduled on this timer. jtulach@1405: * jtulach@1405: * @return the number of tasks removed from the queue. jtulach@1405: * @since 1.5 jtulach@1405: */ jtulach@1405: public int purge() { jtulach@1405: int result = 0; jtulach@1405: jtulach@1405: synchronized(queue) { jtulach@1405: for (int i = queue.size(); i > 0; i--) { jtulach@1405: if (queue.get(i).state == TimerTask.CANCELLED) { jtulach@1405: queue.quickRemove(i); jtulach@1405: result++; jtulach@1405: } jtulach@1405: } jtulach@1405: jtulach@1405: if (result != 0) jtulach@1405: queue.heapify(); jtulach@1405: } jtulach@1405: jtulach@1405: return result; jtulach@1405: } jtulach@1405: } jtulach@1405: jtulach@1405: /** jtulach@1405: * This "helper class" implements the timer's task execution thread, which jtulach@1405: * waits for tasks on the timer queue, executions them when they fire, jtulach@1405: * reschedules repeating tasks, and removes cancelled tasks and spent jtulach@1405: * non-repeating tasks from the queue. jtulach@1405: */ jtulach@1405: class TimerThread extends Thread { jtulach@1405: /** jtulach@1405: * This flag is set to false by the reaper to inform us that there jtulach@1405: * are no more live references to our Timer object. Once this flag jtulach@1405: * is true and there are no more tasks in our queue, there is no jtulach@1405: * work left for us to do, so we terminate gracefully. Note that jtulach@1405: * this field is protected by queue's monitor! jtulach@1405: */ jtulach@1405: boolean newTasksMayBeScheduled = true; jtulach@1405: jtulach@1405: /** jtulach@1405: * Our Timer's queue. We store this reference in preference to jtulach@1405: * a reference to the Timer so the reference graph remains acyclic. jtulach@1405: * Otherwise, the Timer would never be garbage-collected and this jtulach@1405: * thread would never go away. jtulach@1405: */ jtulach@1405: private TaskQueue queue; jtulach@1405: jtulach@1405: TimerThread(TaskQueue queue) { jtulach@1405: this.queue = queue; jtulach@1405: } jtulach@1405: jtulach@1405: public void run() { jtulach@1405: try { jtulach@1405: mainLoop(); jtulach@1405: } finally { jtulach@1405: // Someone killed this Thread, behave as if Timer cancelled jtulach@1405: synchronized(queue) { jtulach@1405: newTasksMayBeScheduled = false; jtulach@1405: queue.clear(); // Eliminate obsolete references jtulach@1405: } jtulach@1405: } jtulach@1405: } jtulach@1405: jtulach@1405: /** jtulach@1405: * The main timer loop. (See class comment.) jtulach@1405: */ jtulach@1405: private void mainLoop() { jtulach@1405: while (true) { jtulach@1405: try { jtulach@1405: TimerTask task; jtulach@1405: boolean taskFired; jtulach@1405: synchronized(queue) { jtulach@1405: // Wait for queue to become non-empty jtulach@1405: while (queue.isEmpty() && newTasksMayBeScheduled) jtulach@1405: queue.wait(); jtulach@1405: if (queue.isEmpty()) jtulach@1405: break; // Queue is empty and will forever remain; die jtulach@1405: jtulach@1405: // Queue nonempty; look at first evt and do the right thing jtulach@1405: long currentTime, executionTime; jtulach@1405: task = queue.getMin(); jtulach@1405: synchronized(task.lock) { jtulach@1405: if (task.state == TimerTask.CANCELLED) { jtulach@1405: queue.removeMin(); jtulach@1405: continue; // No action required, poll queue again jtulach@1405: } jtulach@1405: currentTime = System.currentTimeMillis(); jtulach@1405: executionTime = task.nextExecutionTime; jtulach@1405: if (taskFired = (executionTime<=currentTime)) { jtulach@1405: if (task.period == 0) { // Non-repeating, remove jtulach@1405: queue.removeMin(); jtulach@1405: task.state = TimerTask.EXECUTED; jtulach@1405: } else { // Repeating task, reschedule jtulach@1405: queue.rescheduleMin( jtulach@1405: task.period<0 ? currentTime - task.period jtulach@1405: : executionTime + task.period); jtulach@1405: } jtulach@1405: } jtulach@1405: } jtulach@1405: if (!taskFired) // Task hasn't yet fired; wait jtulach@1405: queue.wait(executionTime - currentTime); jtulach@1405: } jtulach@1405: if (taskFired) // Task fired; run it, holding no locks jtulach@1405: task.run(); jtulach@1405: } catch(InterruptedException e) { jtulach@1405: } jtulach@1405: } jtulach@1405: } jtulach@1405: } jtulach@1405: jtulach@1405: /** jtulach@1405: * This class represents a timer task queue: a priority queue of TimerTasks, jtulach@1405: * ordered on nextExecutionTime. Each Timer object has one of these, which it jtulach@1405: * shares with its TimerThread. Internally this class uses a heap, which jtulach@1405: * offers log(n) performance for the add, removeMin and rescheduleMin jtulach@1405: * operations, and constant time performance for the getMin operation. jtulach@1405: */ jtulach@1405: class TaskQueue { jtulach@1405: /** jtulach@1405: * Priority queue represented as a balanced binary heap: the two children jtulach@1405: * of queue[n] are queue[2*n] and queue[2*n+1]. The priority queue is jtulach@1405: * ordered on the nextExecutionTime field: The TimerTask with the lowest jtulach@1405: * nextExecutionTime is in queue[1] (assuming the queue is nonempty). For jtulach@1405: * each node n in the heap, and each descendant of n, d, jtulach@1405: * n.nextExecutionTime <= d.nextExecutionTime. jtulach@1405: */ jtulach@1405: private TimerTask[] queue = new TimerTask[128]; jtulach@1405: jtulach@1405: /** jtulach@1405: * The number of tasks in the priority queue. (The tasks are stored in jtulach@1405: * queue[1] up to queue[size]). jtulach@1405: */ jtulach@1405: private int size = 0; jtulach@1405: jtulach@1405: /** jtulach@1405: * Returns the number of tasks currently on the queue. jtulach@1405: */ jtulach@1405: int size() { jtulach@1405: return size; jtulach@1405: } jtulach@1405: jtulach@1405: /** jtulach@1405: * Adds a new task to the priority queue. jtulach@1405: */ jtulach@1405: void add(TimerTask task) { jtulach@1405: // Grow backing store if necessary jtulach@1405: if (size + 1 == queue.length) jtulach@1405: queue = Arrays.copyOf(queue, 2*queue.length); jtulach@1405: jtulach@1405: queue[++size] = task; jtulach@1405: fixUp(size); jtulach@1405: } jtulach@1405: jtulach@1405: /** jtulach@1405: * Return the "head task" of the priority queue. (The head task is an jtulach@1405: * task with the lowest nextExecutionTime.) jtulach@1405: */ jtulach@1405: TimerTask getMin() { jtulach@1405: return queue[1]; jtulach@1405: } jtulach@1405: jtulach@1405: /** jtulach@1405: * Return the ith task in the priority queue, where i ranges from 1 (the jtulach@1405: * head task, which is returned by getMin) to the number of tasks on the jtulach@1405: * queue, inclusive. jtulach@1405: */ jtulach@1405: TimerTask get(int i) { jtulach@1405: return queue[i]; jtulach@1405: } jtulach@1405: jtulach@1405: /** jtulach@1405: * Remove the head task from the priority queue. jtulach@1405: */ jtulach@1405: void removeMin() { jtulach@1405: queue[1] = queue[size]; jtulach@1405: queue[size--] = null; // Drop extra reference to prevent memory leak jtulach@1405: fixDown(1); jtulach@1405: } jtulach@1405: jtulach@1405: /** jtulach@1405: * Removes the ith element from queue without regard for maintaining jtulach@1405: * the heap invariant. Recall that queue is one-based, so jtulach@1405: * 1 <= i <= size. jtulach@1405: */ jtulach@1405: void quickRemove(int i) { jtulach@1405: assert i <= size; jtulach@1405: jtulach@1405: queue[i] = queue[size]; jtulach@1405: queue[size--] = null; // Drop extra ref to prevent memory leak jtulach@1405: } jtulach@1405: jtulach@1405: /** jtulach@1405: * Sets the nextExecutionTime associated with the head task to the jtulach@1405: * specified value, and adjusts priority queue accordingly. jtulach@1405: */ jtulach@1405: void rescheduleMin(long newTime) { jtulach@1405: queue[1].nextExecutionTime = newTime; jtulach@1405: fixDown(1); jtulach@1405: } jtulach@1405: jtulach@1405: /** jtulach@1405: * Returns true if the priority queue contains no elements. jtulach@1405: */ jtulach@1405: boolean isEmpty() { jtulach@1405: return size==0; jtulach@1405: } jtulach@1405: jtulach@1405: /** jtulach@1405: * Removes all elements from the priority queue. jtulach@1405: */ jtulach@1405: void clear() { jtulach@1405: // Null out task references to prevent memory leak jtulach@1405: for (int i=1; i<=size; i++) jtulach@1405: queue[i] = null; jtulach@1405: jtulach@1405: size = 0; jtulach@1405: } jtulach@1405: jtulach@1405: /** jtulach@1405: * Establishes the heap invariant (described above) assuming the heap jtulach@1405: * satisfies the invariant except possibly for the leaf-node indexed by k jtulach@1405: * (which may have a nextExecutionTime less than its parent's). jtulach@1405: * jtulach@1405: * This method functions by "promoting" queue[k] up the hierarchy jtulach@1405: * (by swapping it with its parent) repeatedly until queue[k]'s jtulach@1405: * nextExecutionTime is greater than or equal to that of its parent. jtulach@1405: */ jtulach@1405: private void fixUp(int k) { jtulach@1405: while (k > 1) { jtulach@1405: int j = k >> 1; jtulach@1405: if (queue[j].nextExecutionTime <= queue[k].nextExecutionTime) jtulach@1405: break; jtulach@1405: TimerTask tmp = queue[j]; queue[j] = queue[k]; queue[k] = tmp; jtulach@1405: k = j; jtulach@1405: } jtulach@1405: } jtulach@1405: jtulach@1405: /** jtulach@1405: * Establishes the heap invariant (described above) in the subtree jtulach@1405: * rooted at k, which is assumed to satisfy the heap invariant except jtulach@1405: * possibly for node k itself (which may have a nextExecutionTime greater jtulach@1405: * than its children's). jtulach@1405: * jtulach@1405: * This method functions by "demoting" queue[k] down the hierarchy jtulach@1405: * (by swapping it with its smaller child) repeatedly until queue[k]'s jtulach@1405: * nextExecutionTime is less than or equal to those of its children. jtulach@1405: */ jtulach@1405: private void fixDown(int k) { jtulach@1405: int j; jtulach@1405: while ((j = k << 1) <= size && j > 0) { jtulach@1405: if (j < size && jtulach@1405: queue[j].nextExecutionTime > queue[j+1].nextExecutionTime) jtulach@1405: j++; // j indexes smallest kid jtulach@1405: if (queue[k].nextExecutionTime <= queue[j].nextExecutionTime) jtulach@1405: break; jtulach@1405: TimerTask tmp = queue[j]; queue[j] = queue[k]; queue[k] = tmp; jtulach@1405: k = j; jtulach@1405: } jtulach@1405: } jtulach@1405: jtulach@1405: /** jtulach@1405: * Establishes the heap invariant (described above) in the entire tree, jtulach@1405: * assuming nothing about the order of the elements prior to the call. jtulach@1405: */ jtulach@1405: void heapify() { jtulach@1405: for (int i = size/2; i >= 1; i--) jtulach@1405: fixDown(i); jtulach@1405: } jtulach@1405: }