|
From: <ls...@us...> - 2007-09-15 21:45:22
|
Revision: 3504
http://jnode.svn.sourceforge.net/jnode/?rev=3504&view=rev
Author: lsantha
Date: 2007-09-15 14:45:19 -0700 (Sat, 15 Sep 2007)
Log Message:
-----------
Solution for the bug where jnode crashes after the gc is executed after the ping command.
Added Paths:
-----------
trunk/core/src/openjdk/java/java/util/Timer.java
trunk/core/src/openjdk/java/java/util/TimerTask.java
Removed Paths:
-------------
trunk/core/src/classpath/java/java/util/Timer.java
trunk/core/src/classpath/java/java/util/TimerTask.java
Deleted: trunk/core/src/classpath/java/java/util/Timer.java
===================================================================
--- trunk/core/src/classpath/java/java/util/Timer.java 2007-09-15 19:58:16 UTC (rev 3503)
+++ trunk/core/src/classpath/java/java/util/Timer.java 2007-09-15 21:45:19 UTC (rev 3504)
@@ -1,704 +0,0 @@
-/* Timer.java -- Timer that runs TimerTasks at a later time.
- Copyright (C) 2000, 2001, 2005 Free Software Foundation, Inc.
-
-This file is part of GNU Classpath.
-
-GNU Classpath is free software; you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation; either version 2, or (at your option)
-any later version.
-
-GNU Classpath is distributed in the hope that it will be useful, but
-WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with GNU Classpath; see the file COPYING. If not, write to the
-Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-02110-1301 USA.
-
-Linking this library statically or dynamically with other modules is
-making a combined work based on this library. Thus, the terms and
-conditions of the GNU General Public License cover the whole
-combination.
-
-As a special exception, the copyright holders of this library give you
-permission to link this library with independent modules to produce an
-executable, regardless of the license terms of these independent
-modules, and to copy and distribute the resulting executable under
-terms of your choice, provided that you also meet, for each linked
-independent module, the terms and conditions of the license of that
-module. An independent module is a module which is not derived from
-or based on this library. If you modify this library, you may extend
-this exception to your version of the library, but you are not
-obligated to do so. If you do not wish to do so, delete this
-exception statement from your version. */
-
-package java.util;
-
-/**
- * Timer that can run TimerTasks at a later time.
- * TimerTasks can be scheduled for one time execution at some time in the
- * future. They can be scheduled to be rescheduled at a time period after the
- * task was last executed. Or they can be scheduled to be executed repeatedly
- * at a fixed rate.
- * <p>
- * The normal scheduling will result in a more or less even delay in time
- * between successive executions, but the executions could drift in time if
- * the task (or other tasks) takes a long time to execute. Fixed delay
- * scheduling guarantees more or less that the task will be executed at a
- * specific time, but if there is ever a delay in execution then the period
- * between successive executions will be shorter. The first method of
- * repeated scheduling is preferred for repeated tasks in response to user
- * interaction, the second method of repeated scheduling is preferred for tasks
- * that act like alarms.
- * <p>
- * The Timer keeps a binary heap as a task priority queue which means that
- * scheduling and serving of a task in a queue of n tasks costs O(log n).
- *
- * @see TimerTask
- * @since 1.3
- * @author Mark Wielaard (ma...@kl...)
- */
-public class Timer
-{
- /**
- * Priority Task Queue.
- * TimerTasks are kept in a binary heap.
- * The scheduler calls sleep() on the queue when it has nothing to do or
- * has to wait. A sleeping scheduler can be notified by calling interrupt()
- * which is automatically called by the enqueue(), cancel() and
- * timerFinalized() methods.
- */
- private static final class TaskQueue
- {
- /** Default size of this queue */
- private static final int DEFAULT_SIZE = 32;
-
- /** Whether to return null when there is nothing in the queue */
- private boolean nullOnEmpty;
-
- /**
- * The heap containing all the scheduled TimerTasks
- * sorted by the TimerTask.scheduled field.
- * Null when the stop() method has been called.
- */
- private TimerTask heap[];
-
- /**
- * The actual number of elements in the heap
- * Can be less then heap.length.
- * Note that heap[0] is used as a sentinel.
- */
- private int elements;
-
- /**
- * Creates a TaskQueue of default size without any elements in it.
- */
- public TaskQueue()
- {
- heap = new TimerTask[DEFAULT_SIZE];
- elements = 0;
- nullOnEmpty = false;
- }
-
- /**
- * Adds a TimerTask at the end of the heap.
- * Grows the heap if necessary by doubling the heap in size.
- */
- private void add(TimerTask task)
- {
- elements++;
- if (elements == heap.length)
- {
- TimerTask new_heap[] = new TimerTask[heap.length * 2];
- System.arraycopy(heap, 0, new_heap, 0, heap.length);
- heap = new_heap;
- }
- heap[elements] = task;
- }
-
- /**
- * Removes the last element from the heap.
- * Shrinks the heap in half if
- * elements+DEFAULT_SIZE/2 <= heap.length/4.
- */
- private void remove()
- {
- // clear the entry first
- heap[elements] = null;
- elements--;
- if (elements + DEFAULT_SIZE / 2 <= (heap.length / 4))
- {
- TimerTask new_heap[] = new TimerTask[heap.length / 2];
- System.arraycopy(heap, 0, new_heap, 0, elements + 1);
- heap = new_heap;
- }
- }
-
- /**
- * Adds a task to the queue and puts it at the correct place
- * in the heap.
- */
- public synchronized void enqueue(TimerTask task)
- {
- // Check if it is legal to add another element
- if (heap == null)
- {
- throw new IllegalStateException
- ("cannot enqueue when stop() has been called on queue");
- }
-
- heap[0] = task; // sentinel
- add(task); // put the new task at the end
- // Now push the task up in the heap until it has reached its place
- int child = elements;
- int parent = child / 2;
- while (heap[parent].scheduled > task.scheduled)
- {
- heap[child] = heap[parent];
- child = parent;
- parent = child / 2;
- }
- // This is the correct place for the new task
- heap[child] = task;
- heap[0] = null; // clear sentinel
- // Maybe sched() is waiting for a new element
- this.notify();
- }
-
- /**
- * Returns the top element of the queue.
- * Can return null when no task is in the queue.
- */
- private TimerTask top()
- {
- if (elements == 0)
- {
- return null;
- }
- else
- {
- return heap[1];
- }
- }
-
- /**
- * Returns the top task in the Queue.
- * Removes the element from the heap and reorders the heap first.
- * Can return null when there is nothing in the queue.
- */
- public synchronized TimerTask serve()
- {
- // The task to return
- TimerTask task = null;
-
- while (task == null)
- {
- // Get the next task
- task = top();
-
- // return null when asked to stop
- // or if asked to return null when the queue is empty
- if ((heap == null) || (task == null && nullOnEmpty))
- {
- return null;
- }
-
- // Do we have a task?
- if (task != null)
- {
- // The time to wait until the task should be served
- long time = task.scheduled - System.currentTimeMillis();
- if (time > 0)
- {
- // This task should not yet be served
- // So wait until this task is ready
- // or something else happens to the queue
- task = null; // set to null to make sure we call top()
- try
- {
- this.wait(time);
- }
- catch (InterruptedException _)
- {
- }
- }
- }
- else
- {
- // wait until a task is added
- // or something else happens to the queue
- try
- {
- this.wait();
- }
- catch (InterruptedException _)
- {
- }
- }
- }
-
- // reconstruct the heap
- TimerTask lastTask = heap[elements];
- remove();
-
- // drop lastTask at the beginning and move it down the heap
- int parent = 1;
- int child = 2;
- heap[1] = lastTask;
- while (child <= elements)
- {
- if (child < elements)
- {
- if (heap[child].scheduled > heap[child + 1].scheduled)
- {
- child++;
- }
- }
-
- if (lastTask.scheduled <= heap[child].scheduled)
- break; // found the correct place (the parent) - done
-
- heap[parent] = heap[child];
- parent = child;
- child = parent * 2;
- }
-
- // this is the correct new place for the lastTask
- heap[parent] = lastTask;
-
- // return the task
- return task;
- }
-
- /**
- * When nullOnEmpty is true the serve() method will return null when
- * there are no tasks in the queue, otherwise it will wait until
- * a new element is added to the queue. It is used to indicate to
- * the scheduler that no new tasks will ever be added to the queue.
- */
- public synchronized void setNullOnEmpty(boolean nullOnEmpty)
- {
- this.nullOnEmpty = nullOnEmpty;
- this.notify();
- }
-
- /**
- * When this method is called the current and all future calls to
- * serve() will return null. It is used to indicate to the Scheduler
- * that it should stop executing since no more tasks will come.
- */
- public synchronized void stop()
- {
- this.heap = null;
- this.elements = 0;
- this.notify();
- }
-
- /**
- * Remove all canceled tasks from the queue.
- */
- public synchronized int purge()
- {
- int removed = 0;
- // Null out any elements that are canceled. Skip element 0 as
- // it is the sentinel.
- for (int i = elements; i > 0; --i)
- {
- if (heap[i].scheduled < 0)
- {
- ++removed;
-
- // Remove an element by pushing the appropriate child
- // into place, and then iterating to the bottom of the
- // tree.
- int index = i;
- while (heap[index] != null)
- {
- int child = 2 * index;
- if (child >= heap.length)
- {
- // Off end; we're done.
- heap[index] = null;
- break;
- }
-
- if (child + 1 >= heap.length || heap[child + 1] == null)
- {
- // Nothing -- we're done.
- }
- else if (heap[child] == null
- || (heap[child].scheduled
- > heap[child + 1].scheduled))
- ++child;
- heap[index] = heap[child];
- index = child;
- }
- }
- }
-
- // Make a new heap if we shrank enough.
- int newLen = heap.length;
- while (elements - removed + DEFAULT_SIZE / 2 <= newLen / 4)
- newLen /= 2;
- if (newLen != heap.length)
- {
- TimerTask[] newHeap = new TimerTask[newLen];
- System.arraycopy(heap, 0, newHeap, 0, elements + 1);
- heap = newHeap;
- }
-
- return removed;
- }
- } // TaskQueue
-
- /**
- * The scheduler that executes all the tasks on a particular TaskQueue,
- * reschedules any repeating tasks and that waits when no task has to be
- * executed immediately. Stops running when canceled or when the parent
- * Timer has been finalized and no more tasks have to be executed.
- */
- private static final class Scheduler implements Runnable
- {
- // The priority queue containing all the TimerTasks.
- private TaskQueue queue;
-
- /**
- * Creates a new Scheduler that will schedule the tasks on the
- * given TaskQueue.
- */
- public Scheduler(TaskQueue queue)
- {
- this.queue = queue;
- }
-
- public void run()
- {
- TimerTask task;
- while ((task = queue.serve()) != null)
- {
- // If this task has not been canceled
- if (task.scheduled >= 0)
- {
-
- // Mark execution time
- task.lastExecutionTime = task.scheduled;
-
- // Repeatable task?
- if (task.period < 0)
- {
- // Last time this task is executed
- task.scheduled = -1;
- }
-
- // Run the task
- try
- {
- task.run();
- }
- catch (ThreadDeath death)
- {
- // If an exception escapes, the Timer becomes invalid.
- queue.stop();
- throw death;
- }
- catch (Throwable t)
- {
- // If an exception escapes, the Timer becomes invalid.
- queue.stop();
- }
- }
-
- // Calculate next time and possibly re-enqueue.
- if (task.scheduled >= 0)
- {
- if (task.fixed)
- {
- task.scheduled += task.period;
- }
- else
- {
- task.scheduled = task.period + System.currentTimeMillis();
- }
-
- try
- {
- queue.enqueue(task);
- }
- catch (IllegalStateException ise)
- {
- // Ignore. Apparently the Timer queue has been stopped.
- }
- }
- }
- }
- } // Scheduler
-
- // Number of Timers created.
- // Used for creating nice Thread names.
- private static int nr;
-
- // The queue that all the tasks are put in.
- // Given to the scheduler
- private TaskQueue queue;
-
- // The Scheduler that does all the real work
- private Scheduler scheduler;
-
- // Used to run the scheduler.
- // Also used to checked if the Thread is still running by calling
- // thread.isAlive(). Sometimes a Thread is suddenly killed by the system
- // (if it belonged to an Applet).
- private Thread thread;
-
- // When cancelled we don't accept any more TimerTasks.
- private boolean canceled;
-
- /**
- * Creates a new Timer with a non daemon Thread as Scheduler, with normal
- * priority and a default name.
- */
- public Timer()
- {
- this(false);
- }
-
- /**
- * Creates a new Timer with a daemon Thread as scheduler if daemon is true,
- * with normal priority and a default name.
- */
- public Timer(boolean daemon)
- {
- this(daemon, Thread.NORM_PRIORITY);
- }
-
- /**
- * Create a new Timer whose Thread has the indicated name. It will have
- * normal priority and will not be a daemon thread.
- * @param name the name of the Thread
- * @since 1.5
- */
- public Timer(String name)
- {
- this(false, Thread.NORM_PRIORITY, name);
- }
-
- /**
- * Create a new Timer whose Thread has the indicated name. It will have
- * normal priority. The boolean argument controls whether or not it
- * will be a daemon thread.
- * @param name the name of the Thread
- * @param daemon true if the Thread should be a daemon thread
- * @since 1.5
- */
- public Timer(String name, boolean daemon)
- {
- this(daemon, Thread.NORM_PRIORITY, name);
- }
-
- /**
- * Creates a new Timer with a daemon Thread as scheduler if daemon is true,
- * with the priority given and a default name.
- */
- private Timer(boolean daemon, int priority)
- {
- this(daemon, priority, "Timer-" + (++nr));
- }
-
- /**
- * Creates a new Timer with a daemon Thread as scheduler if daemon is true,
- * with the priority and name given.E
- */
- private Timer(boolean daemon, int priority, String name)
- {
- canceled = false;
- queue = new TaskQueue();
- scheduler = new Scheduler(queue);
- thread = new Thread(scheduler, name);
- thread.setDaemon(daemon);
- thread.setPriority(priority);
- thread.start();
- }
-
- /**
- * Cancels the execution of the scheduler. If a task is executing it will
- * normally finish execution, but no other tasks will be executed and no
- * more tasks can be scheduled.
- */
- public void cancel()
- {
- canceled = true;
- queue.stop();
- }
-
- /**
- * Schedules the task at Time time, repeating every period
- * milliseconds if period is positive and at a fixed rate if fixed is true.
- *
- * @exception IllegalArgumentException if time is negative
- * @exception IllegalStateException if the task was already scheduled or
- * canceled or this Timer is canceled or the scheduler thread has died
- */
- private void schedule(TimerTask task, long time, long period, boolean fixed)
- {
- if (time < 0)
- throw new IllegalArgumentException("negative time");
-
- if (task.scheduled == 0 && task.lastExecutionTime == -1)
- {
- task.scheduled = time;
- task.period = period;
- task.fixed = fixed;
- }
- else
- {
- throw new IllegalStateException
- ("task was already scheduled or canceled");
- }
-
- if (!this.canceled && this.thread != null)
- {
- queue.enqueue(task);
- }
- else
- {
- throw new IllegalStateException
- ("timer was canceled or scheduler thread has died");
- }
- }
-
- private static void positiveDelay(long delay)
- {
- if (delay < 0)
- {
- throw new IllegalArgumentException("delay is negative");
- }
- }
-
- private static void positivePeriod(long period)
- {
- if (period < 0)
- {
- throw new IllegalArgumentException("period is negative");
- }
- }
-
- /**
- * Schedules the task at the specified data for one time execution.
- *
- * @exception IllegalArgumentException if date.getTime() is negative
- * @exception IllegalStateException if the task was already scheduled or
- * canceled or this Timer is canceled or the scheduler thread has died
- */
- public void schedule(TimerTask task, Date date)
- {
- long time = date.getTime();
- schedule(task, time, -1, false);
- }
-
- /**
- * Schedules the task at the specified date and reschedules the task every
- * period milliseconds after the last execution of the task finishes until
- * this timer or the task is canceled.
- *
- * @exception IllegalArgumentException if period or date.getTime() is
- * negative
- * @exception IllegalStateException if the task was already scheduled or
- * canceled or this Timer is canceled or the scheduler thread has died
- */
- public void schedule(TimerTask task, Date date, long period)
- {
- positivePeriod(period);
- long time = date.getTime();
- schedule(task, time, period, false);
- }
-
- /**
- * Schedules the task after the specified delay milliseconds for one time
- * execution.
- *
- * @exception IllegalArgumentException if delay or
- * System.currentTimeMillis + delay is negative
- * @exception IllegalStateException if the task was already scheduled or
- * canceled or this Timer is canceled or the scheduler thread has died
- */
- public void schedule(TimerTask task, long delay)
- {
- positiveDelay(delay);
- long time = System.currentTimeMillis() + delay;
- schedule(task, time, -1, false);
- }
-
- /**
- * Schedules the task after the delay milliseconds and reschedules the
- * task every period milliseconds after the last execution of the task
- * finishes until this timer or the task is canceled.
- *
- * @exception IllegalArgumentException if delay or period is negative
- * @exception IllegalStateException if the task was already scheduled or
- * canceled or this Timer is canceled or the scheduler thread has died
- */
- public void schedule(TimerTask task, long delay, long period)
- {
- positiveDelay(delay);
- positivePeriod(period);
- long time = System.currentTimeMillis() + delay;
- schedule(task, time, period, false);
- }
-
- /**
- * Schedules the task at the specified date and reschedules the task at a
- * fixed rate every period milliseconds until this timer or the task is
- * canceled.
- *
- * @exception IllegalArgumentException if period or date.getTime() is
- * negative
- * @exception IllegalStateException if the task was already scheduled or
- * canceled or this Timer is canceled or the scheduler thread has died
- */
- public void scheduleAtFixedRate(TimerTask task, Date date, long period)
- {
- positivePeriod(period);
- long time = date.getTime();
- schedule(task, time, period, true);
- }
-
- /**
- * Schedules the task after the delay milliseconds and reschedules the task
- * at a fixed rate every period milliseconds until this timer or the task
- * is canceled.
- *
- * @exception IllegalArgumentException if delay or
- * System.currentTimeMillis + delay is negative
- * @exception IllegalStateException if the task was already scheduled or
- * canceled or this Timer is canceled or the scheduler thread has died
- */
- public void scheduleAtFixedRate(TimerTask task, long delay, long period)
- {
- positiveDelay(delay);
- positivePeriod(period);
- long time = System.currentTimeMillis() + delay;
- schedule(task, time, period, true);
- }
-
- /**
- * Tells the scheduler that the Timer task died
- * so there will be no more new tasks scheduled.
- */
- protected void finalize() throws Throwable
- {
- queue.setNullOnEmpty(true);
- }
-
- /**
- * Removes all cancelled tasks from the queue.
- * @return the number of tasks removed
- * @since 1.5
- */
- public int purge()
- {
- return queue.purge();
- }
-}
Deleted: trunk/core/src/classpath/java/java/util/TimerTask.java
===================================================================
--- trunk/core/src/classpath/java/java/util/TimerTask.java 2007-09-15 19:58:16 UTC (rev 3503)
+++ trunk/core/src/classpath/java/java/util/TimerTask.java 2007-09-15 21:45:19 UTC (rev 3504)
@@ -1,145 +0,0 @@
-/* TimerTask.java -- Task that can be run at a later time if given to a Timer.
- Copyright (C) 2000 Free Software Foundation, Inc.
-
-This file is part of GNU Classpath.
-
-GNU Classpath is free software; you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation; either version 2, or (at your option)
-any later version.
-
-GNU Classpath is distributed in the hope that it will be useful, but
-WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with GNU Classpath; see the file COPYING. If not, write to the
-Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-02110-1301 USA.
-
-Linking this library statically or dynamically with other modules is
-making a combined work based on this library. Thus, the terms and
-conditions of the GNU General Public License cover the whole
-combination.
-
-As a special exception, the copyright holders of this library give you
-permission to link this library with independent modules to produce an
-executable, regardless of the license terms of these independent
-modules, and to copy and distribute the resulting executable under
-terms of your choice, provided that you also meet, for each linked
-independent module, the terms and conditions of the license of that
-module. An independent module is a module which is not derived from
-or based on this library. If you modify this library, you may extend
-this exception to your version of the library, but you are not
-obligated to do so. If you do not wish to do so, delete this
-exception statement from your version. */
-
-package java.util;
-
-/**
- * Task that can be run at a later time if given to a Timer.
- * The TimerTask must implement a run method that will be called by the
- * Timer when the task is scheduled for execution. The task can check when
- * it should have been scheduled and cancel itself when no longer needed.
- * <p>
- * Example:
- * <pre>
- * Timer timer = new Timer();
- * TimerTask task = new TimerTask() {
- * public void run() {
- * if (this.scheduledExecutionTime() < System.currentTimeMillis() + 500)
- * // Do something
- * else
- * // Complain: We are more then half a second late!
- * if (someStopCondition)
- * this.cancel(); // This was our last execution
- * };
- * timer.scheduleAtFixedRate(task, 1000, 1000); // schedule every second
- * </pre>
- * <p>
- * Note that a TimerTask object is a one shot object and can only given once
- * to a Timer. (The Timer will use the TimerTask object for bookkeeping,
- * in this implementation).
- * <p>
- * This class also implements <code>Runnable</code> to make it possible to
- * give a TimerTask directly as a target to a <code>Thread</code>.
- *
- * @see Timer
- * @since 1.3
- * @author Mark Wielaard (ma...@kl...)
- */
-public abstract class TimerTask implements Runnable
-{
- /**
- * If positive the next time this task should be run.
- * If negative this TimerTask is canceled or executed for the last time.
- */
- long scheduled;
-
- /**
- * If positive the last time this task was run.
- * If negative this TimerTask has not yet been scheduled.
- */
- long lastExecutionTime;
-
- /**
- * If positive the number of milliseconds between runs of this task.
- * If -1 this task doesn't have to be run more then once.
- */
- long period;
-
- /**
- * If true the next time this task should be run is relative to
- * the last scheduled time, otherwise it can drift in time.
- */
- boolean fixed;
-
- /**
- * Creates a TimerTask and marks it as not yet scheduled.
- */
- protected TimerTask()
- {
- this.scheduled = 0;
- this.lastExecutionTime = -1;
- }
-
- /**
- * Marks the task as canceled and prevents any further execution.
- * Returns true if the task was scheduled for any execution in the future
- * and this cancel operation prevents that execution from happening.
- * <p>
- * A task that has been canceled can never be scheduled again.
- * <p>
- * In this implementation the TimerTask it is possible that the Timer does
- * keep a reference to the TimerTask until the first time the TimerTask
- * is actually scheduled. But the reference will disappear immediatly when
- * cancel is called from within the TimerTask run method.
- */
- public boolean cancel()
- {
- boolean prevented_execution = (this.scheduled >= 0);
- this.scheduled = -1;
- return prevented_execution;
- }
-
- /**
- * Method that is called when this task is scheduled for execution.
- */
- public abstract void run();
-
- /**
- * Returns the last time this task was scheduled or (when called by the
- * task from the run method) the time the current execution of the task
- * was scheduled. When the task has not yet run the return value is
- * undefined.
- * <p>
- * Can be used (when the task is scheduled at fixed rate) to see the
- * difference between the requested schedule time and the actual time
- * that can be found with <code>System.currentTimeMillis()</code>.
- */
- public long scheduledExecutionTime()
- {
- return lastExecutionTime;
- }
-}
Added: trunk/core/src/openjdk/java/java/util/Timer.java
===================================================================
--- trunk/core/src/openjdk/java/java/util/Timer.java (rev 0)
+++ trunk/core/src/openjdk/java/java/util/Timer.java 2007-09-15 21:45:19 UTC (rev 3504)
@@ -0,0 +1,700 @@
+/*
+ * Copyright 1999-2007 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package java.util;
+import java.util.Date;
+
+/**
+ * A facility for threads to schedule tasks for future execution in a
+ * background thread. Tasks may be scheduled for one-time execution, or for
+ * repeated execution at regular intervals.
+ *
+ * <p>Corresponding to each <tt>Timer</tt> object is a single background
+ * thread that is used to execute all of the timer's tasks, sequentially.
+ * Timer tasks should complete quickly. If a timer task takes excessive time
+ * to complete, it "hogs" the timer's task execution thread. This can, in
+ * turn, delay the execution of subsequent tasks, which may "bunch up" and
+ * execute in rapid succession when (and if) the offending task finally
+ * completes.
+ *
+ * <p>After the last live reference to a <tt>Timer</tt> object goes away
+ * <i>and</i> all outstanding tasks have completed execution, the timer's task
+ * execution thread terminates gracefully (and becomes subject to garbage
+ * collection). However, this can take arbitrarily long to occur. By
+ * default, the task execution thread does not run as a <i>daemon thread</i>,
+ * so it is capable of keeping an application from terminating. If a caller
+ * wants to terminate a timer's task execution thread rapidly, the caller
+ * should invoke the timer's <tt>cancel</tt> method.
+ *
+ * <p>If the timer's task execution thread terminates unexpectedly, for
+ * example, because its <tt>stop</tt> method is invoked, any further
+ * attempt to schedule a task on the timer will result in an
+ * <tt>IllegalStateException</tt>, as if the timer's <tt>cancel</tt>
+ * method had been invoked.
+ *
+ * <p>This class is thread-safe: multiple threads can share a single
+ * <tt>Timer</tt> object without the need for external synchronization.
+ *
+ * <p>This class does <i>not</i> offer real-time guarantees: it schedules
+ * tasks using the <tt>Object.wait(long)</tt> method.
+ *
+ * <p>Java 5.0 introduced the {@code java.util.concurrent} package and
+ * one of the concurrency utilities therein is the {@link
+ * java.util.concurrent.ScheduledThreadPoolExecutor
+ * ScheduledThreadPoolExecutor} which is a thread pool for repeatedly
+ * executing tasks at a given rate or delay. It is effectively a more
+ * versatile replacement for the {@code Timer}/{@code TimerTask}
+ * combination, as it allows multiple service threads, accepts various
+ * time units, and doesn't require subclassing {@code TimerTask} (just
+ * implement {@code Runnable}). Configuring {@code
+ * ScheduledThreadPoolExecutor} with one thread makes it equivalent to
+ * {@code Timer}.
+ *
+ * <p>Implementation note: This class scales to large numbers of concurrently
+ * scheduled tasks (thousands should present no problem). Internally,
+ * it uses a binary heap to represent its task queue, so the cost to schedule
+ * a task is O(log n), where n is the number of concurrently scheduled tasks.
+ *
+ * <p>Implementation note: All constructors start a timer thread.
+ *
+ * @author Josh Bloch
+ * @version 1.27, 05/05/07
+ * @see TimerTask
+ * @see Object#wait(long)
+ * @since 1.3
+ */
+
+public class Timer {
+ /**
+ * The timer task queue. This data structure is shared with the timer
+ * thread. The timer produces tasks, via its various schedule calls,
+ * and the timer thread consumes, executing timer tasks as appropriate,
+ * and removing them from the queue when they're obsolete.
+ */
+ private TaskQueue queue = new TaskQueue();
+
+ /**
+ * The timer thread.
+ */
+ private TimerThread thread = new TimerThread(queue);
+
+ /**
+ * This object causes the timer's task execution thread to exit
+ * gracefully when there are no live references to the Timer object and no
+ * tasks in the timer queue. It is used in preference to a finalizer on
+ * Timer as such a finalizer would be susceptible to a subclass's
+ * finalizer forgetting to call it.
+ */
+ private Object threadReaper = new Object() {
+ protected void finalize() throws Throwable {
+ synchronized(queue) {
+ thread.newTasksMayBeScheduled = false;
+ queue.notify(); // In case queue is empty.
+ }
+ }
+ };
+
+ /**
+ * This ID is used to generate thread names. (It could be replaced
+ * by an AtomicInteger as soon as they become available.)
+ */
+ private static int nextSerialNumber = 0;
+ private static synchronized int serialNumber() {
+ return nextSerialNumber++;
+ }
+
+ /**
+ * Creates a new timer. The associated thread does <i>not</i>
+ * {@linkplain Thread#setDaemon run as a daemon}.
+ */
+ public Timer() {
+ this("Timer-" + serialNumber());
+ }
+
+ /**
+ * Creates a new timer whose associated thread may be specified to
+ * {@linkplain Thread#setDaemon run as a daemon}.
+ * A daemon thread is called for if the timer will be used to
+ * schedule repeating "maintenance activities", which must be
+ * performed as long as the application is running, but should not
+ * prolong the lifetime of the application.
+ *
+ * @param isDaemon true if the associated thread should run as a daemon.
+ */
+ public Timer(boolean isDaemon) {
+ this("Timer-" + serialNumber(), isDaemon);
+ }
+
+ /**
+ * Creates a new timer whose associated thread has the specified name.
+ * The associated thread does <i>not</i>
+ * {@linkplain Thread#setDaemon run as a daemon}.
+ *
+ * @param name the name of the associated thread
+ * @throws NullPointerException if name is null
+ * @since 1.5
+ */
+ public Timer(String name) {
+ thread.setName(name);
+ thread.start();
+ }
+
+ /**
+ * Creates a new timer whose associated thread has the specified name,
+ * and may be specified to
+ * {@linkplain Thread#setDaemon run as a daemon}.
+ *
+ * @param name the name of the associated thread
+ * @param isDaemon true if the associated thread should run as a daemon
+ * @throws NullPointerException if name is null
+ * @since 1.5
+ */
+ public Timer(String name, boolean isDaemon) {
+ thread.setName(name);
+ thread.setDaemon(isDaemon);
+ thread.start();
+ }
+
+ /**
+ * Schedules the specified task for execution after the specified delay.
+ *
+ * @param task task to be scheduled.
+ * @param delay delay in milliseconds before task is to be executed.
+ * @throws IllegalArgumentException if <tt>delay</tt> is negative, or
+ * <tt>delay + System.currentTimeMillis()</tt> is negative.
+ * @throws IllegalStateException if task was already scheduled or
+ * cancelled, or timer was cancelled.
+ */
+ public void schedule(TimerTask task, long delay) {
+ if (delay < 0)
+ throw new IllegalArgumentException("Negative delay.");
+ sched(task, System.currentTimeMillis()+delay, 0);
+ }
+
+ /**
+ * Schedules the specified task for execution at the specified time. If
+ * the time is in the past, the task is scheduled for immediate execution.
+ *
+ * @param task task to be scheduled.
+ * @param time time at which task is to be executed.
+ * @throws IllegalArgumentException if <tt>time.getTime()</tt> is negative.
+ * @throws IllegalStateException if task was already scheduled or
+ * cancelled, timer was cancelled, or timer thread terminated.
+ */
+ public void schedule(TimerTask task, Date time) {
+ sched(task, time.getTime(), 0);
+ }
+
+ /**
+ * Schedules the specified task for repeated <i>fixed-delay execution</i>,
+ * beginning after the specified delay. Subsequent executions take place
+ * at approximately regular intervals separated by the specified period.
+ *
+ * <p>In fixed-delay execution, each execution is scheduled relative to
+ * the actual execution time of the previous execution. If an execution
+ * is delayed for any reason (such as garbage collection or other
+ * background activity), subsequent executions will be delayed as well.
+ * In the long run, the frequency of execution will generally be slightly
+ * lower than the reciprocal of the specified period (assuming the system
+ * clock underlying <tt>Object.wait(long)</tt> is accurate).
+ *
+ * <p>Fixed-delay execution is appropriate for recurring activities
+ * that require "smoothness." In other words, it is appropriate for
+ * activities where it is more important to keep the frequency accurate
+ * in the short run than in the long run. This includes most animation
+ * tasks, such as blinking a cursor at regular intervals. It also includes
+ * tasks wherein regular activity is performed in response to human
+ * input, such as automatically repeating a character as long as a key
+ * is held down.
+ *
+ * @param task task to be scheduled.
+ * @param delay delay in milliseconds before task is to be executed.
+ * @param period time in milliseconds between successive task executions.
+ * @throws IllegalArgumentException if <tt>delay</tt> is negative, or
+ * <tt>delay + System.currentTimeMillis()</tt> is negative.
+ * @throws IllegalStateException if task was already scheduled or
+ * cancelled, timer was cancelled, or timer thread terminated.
+ */
+ public void schedule(TimerTask task, long delay, long period) {
+ if (delay < 0)
+ throw new IllegalArgumentException("Negative delay.");
+ if (period <= 0)
+ throw new IllegalArgumentException("Non-positive period.");
+ sched(task, System.currentTimeMillis()+delay, -period);
+ }
+
+ /**
+ * Schedules the specified task for repeated <i>fixed-delay execution</i>,
+ * beginning at the specified time. Subsequent executions take place at
+ * approximately regular intervals, separated by the specified period.
+ *
+ * <p>In fixed-delay execution, each execution is scheduled relative to
+ * the actual execution time of the previous execution. If an execution
+ * is delayed for any reason (such as garbage collection or other
+ * background activity), subsequent executions will be delayed as well.
+ * In the long run, the frequency of execution will generally be slightly
+ * lower than the reciprocal of the specified period (assuming the system
+ * clock underlying <tt>Object.wait(long)</tt> is accurate).
+ *
+ * <p>Fixed-delay execution is appropriate for recurring activities
+ * that require "smoothness." In other words, it is appropriate for
+ * activities where it is more important to keep the frequency accurate
+ * in the short run than in the long run. This includes most animation
+ * tasks, such as blinking a cursor at regular intervals. It also includes
+ * tasks wherein regular activity is performed in response to human
+ * input, such as automatically repeating a character as long as a key
+ * is held down.
+ *
+ * @param task task to be scheduled.
+ * @param firstTime First time at which task is to be executed.
+ * @param period time in milliseconds between successive task executions.
+ * @throws IllegalArgumentException if <tt>time.getTime()</tt> is negative.
+ * @throws IllegalStateException if task was already scheduled or
+ * cancelled, timer was cancelled, or timer thread terminated.
+ */
+ public void schedule(TimerTask task, Date firstTime, long period) {
+ if (period <= 0)
+ throw new IllegalArgumentException("Non-positive period.");
+ sched(task, firstTime.getTime(), -period);
+ }
+
+ /**
+ * Schedules the specified task for repeated <i>fixed-rate execution</i>,
+ * beginning after the specified delay. Subsequent executions take place
+ * at approximately regular intervals, separated by the specified period.
+ *
+ * <p>In fixed-rate execution, each execution is scheduled relative to the
+ * scheduled execution time of the initial execution. If an execution is
+ * delayed for any reason (such as garbage collection or other background
+ * activity), two or more executions will occur in rapid succession to
+ * "catch up." In the long run, the frequency of execution will be
+ * exactly the reciprocal of the specified period (assuming the system
+ * clock underlying <tt>Object.wait(long)</tt> is accurate).
+ *
+ * <p>Fixed-rate execution is appropriate for recurring activities that
+ * are sensitive to <i>absolute</i> time, such as ringing a chime every
+ * hour on the hour, or running scheduled maintenance every day at a
+ * particular time. It is also appropriate for recurring activities
+ * where the total time to perform a fixed number of executions is
+ * important, such as a countdown timer that ticks once every second for
+ * ten seconds. Finally, fixed-rate execution is appropriate for
+ * scheduling multiple repeating timer tasks that must remain synchronized
+ * with respect to one another.
+ *
+ * @param task task to be scheduled.
+ * @param delay delay in milliseconds before task is to be executed.
+ * @param period time in milliseconds between successive task executions.
+ * @throws IllegalArgumentException if <tt>delay</tt> is negative, or
+ * <tt>delay + System.currentTimeMillis()</tt> is negative.
+ * @throws IllegalStateException if task was already scheduled or
+ * cancelled, timer was cancelled, or timer thread terminated.
+ */
+ public void scheduleAtFixedRate(TimerTask task, long delay, long period) {
+ if (delay < 0)
+ throw new IllegalArgumentException("Negative delay.");
+ if (period <= 0)
+ throw new IllegalArgumentException("Non-positive period.");
+ sched(task, System.currentTimeMillis()+delay, period);
+ }
+
+ /**
+ * Schedules the specified task for repeated <i>fixed-rate execution</i>,
+ * beginning at the specified time. Subsequent executions take place at
+ * approximately regular intervals, separated by the specified period.
+ *
+ * <p>In fixed-rate execution, each execution is scheduled relative to the
+ * scheduled execution time of the initial execution. If an execution is
+ * delayed for any reason (such as garbage collection or other background
+ * activity), two or more executions will occur in rapid succession to
+ * "catch up." In the long run, the frequency of execution will be
+ * exactly the reciprocal of the specified period (assuming the system
+ * clock underlying <tt>Object.wait(long)</tt> is accurate).
+ *
+ * <p>Fixed-rate execution is appropriate for recurring activities that
+ * are sensitive to <i>absolute</i> time, such as ringing a chime every
+ * hour on the hour, or running scheduled maintenance every day at a
+ * particular time. It is also appropriate for recurring activities
+ * where the total time to perform a fixed number of executions is
+ * important, such as a countdown timer that ticks once every second for
+ * ten seconds. Finally, fixed-rate execution is appropriate for
+ * scheduling multiple repeating timer tasks that must remain synchronized
+ * with respect to one another.
+ *
+ * @param task task to be scheduled.
+ * @param firstTime First time at which task is to be executed.
+ * @param period time in milliseconds between successive task executions.
+ * @throws IllegalArgumentException if <tt>time.getTime()</tt> is negative.
+ * @throws IllegalStateException if task was already scheduled or
+ * cancelled, timer was cancelled, or timer thread terminated.
+ */
+ public void scheduleAtFixedRate(TimerTask task, Date firstTime,
+ long period) {
+ if (period <= 0)
+ throw new IllegalArgumentException("Non-positive period.");
+ sched(task, firstTime.getTime(), period);
+ }
+
+ /**
+ * Schedule the specified timer task for execution at the specified
+ * time with the specified period, in milliseconds. If period is
+ * positive, the task is scheduled for repeated execution; if period is
+ * zero, the task is scheduled for one-time execution. Time is specified
+ * in Date.getTime() format. This method checks timer state, task state,
+ * and initial execution time, but not period.
+ *
+ * @throws IllegalArgumentException if <tt>time()</tt> is negative.
+ * @throws IllegalStateException if task was already scheduled or
+ * cancelled, timer was cancelled, or timer thread terminated.
+ */
+ private void sched(TimerTask task, long time, long period) {
+ if (time < 0)
+ throw new IllegalArgumentException("Illegal execution time.");
+
+ synchronized(queue) {
+ if (!thread.newTasksMayBeScheduled)
+ throw new IllegalStateException("Timer already cancelled.");
+
+ synchronized(task.lock) {
+ if (task.state != TimerTask.VIRGIN)
+ throw new IllegalStateException(
+ "Task already scheduled or cancelled");
+ task.nextExecutionTime = time;
+ task.period = period;
+ task.state = TimerTask.SCHEDULED;
+ }
+
+ queue.add(task);
+ if (queue.getMin() == task)
+ queue.notify();
+ }
+ }
+
+ /**
+ * Terminates this timer, discarding any currently scheduled tasks.
+ * Does not interfere with a currently executing task (if it exists).
+ * Once a timer has been terminated, its execution thread terminates
+ * gracefully, and no more tasks may be scheduled on it.
+ *
+ * <p>Note that calling this method from within the run method of a
+ * timer task that was invoked by this timer absolutely guarantees that
+ * the ongoing task execution is the last task execution that will ever
+ * be performed by this timer.
+ *
+ * <p>This method may be called repeatedly; the second and subsequent
+ * calls have no effect.
+ */
+ public void cancel() {
+ synchronized(queue) {
+ thread.newTasksMayBeScheduled = false;
+ queue.clear();
+ queue.notify(); // In case queue was already empty.
+ }
+ }
+
+ /**
+ * Removes all cancelled tasks from this timer's task queue. <i>Calling
+ * this method has no effect on the behavior of the timer</i>, but
+ * eliminates the references to the cancelled tasks from the queue.
+ * If there are no external references to these tasks, they become
+ * eligible for garbage collection.
+ *
+ * <p>Most programs will have no need to call this method.
+ * It is designed for use by the rare application that cancels a large
+ * number of tasks. Calling this method trades time for space: the
+ * runtime of the method may be proportional to n + c log n, where n
+ * is the number of tasks in the queue and c is the number of cancelled
+ * tasks.
+ *
+ * <p>Note that it is permissible to call this method from within a
+ * a task scheduled on this timer.
+ *
+ * @return the number of tasks removed from the queue.
+ * @since 1.5
+ */
+ public int purge() {
+ int result = 0;
+
+ synchronized(queue) {
+ for (int i = queue.size(); i > 0; i--) {
+ if (queue.get(i).state == TimerTask.CANCELLED) {
+ queue.quickRemove(i);
+ result++;
+ }
+ }
+
+ if (result != 0)
+ queue.heapify();
+ }
+
+ return result;
+ }
+}
+
+/**
+ * This "helper class" implements the timer's task execution thread, which
+ * waits for tasks on the timer queue, executions them when they fire,
+ * reschedules repeating tasks, and removes cancelled tasks and spent
+ * non-repeating tasks from the queue.
+ */
+class TimerThread extends Thread {
+ /**
+ * This flag is set to false by the reaper to inform us that there
+ * are no more live references to our Timer object. Once this flag
+ * is true and there are no more tasks in our queue, there is no
+ * work left for us to do, so we terminate gracefully. Note that
+ * this field is protected by queue's monitor!
+ */
+ boolean newTasksMayBeScheduled = true;
+
+ /**
+ * Our Timer's queue. We store this reference in preference to
+ * a reference to the Timer so the reference graph remains acyclic.
+ * Otherwise, the Timer would never be garbage-collected and this
+ * thread would never go away.
+ */
+ private TaskQueue queue;
+
+ TimerThread(TaskQueue queue) {
+ this.queue = queue;
+ }
+
+ public void run() {
+ try {
+ mainLoop();
+ } finally {
+ // Someone killed this Thread, behave as if Timer cancelled
+ synchronized(queue) {
+ newTasksMayBeScheduled = false;
+ queue.clear(); // Eliminate obsolete references
+ }
+ }
+ }
+
+ /**
+ * The main timer loop. (See class comment.)
+ */
+ private void mainLoop() {
+ while (true) {
+ try {
+ TimerTask task;
+ boolean taskFired;
+ synchronized(queue) {
+ // Wait for queue to become non-empty
+ while (queue.isEmpty() && newTasksMayBeScheduled)
+ queue.wait();
+ if (queue.isEmpty())
+ break; // Queue is empty and will forever remain; die
+
+ // Queue nonempty; look at first evt and do the right thing
+ long currentTime, executionTime;
+ task = queue.getMin();
+ synchronized(task.lock) {
+ if (task.state == TimerTask.CANCELLED) {
+ queue.removeMin();
+ continue; // No action required, poll queue again
+ }
+ currentTime = System.currentTimeMillis();
+ executionTime = task.nextExecutionTime;
+ if (taskFired = (executionTime<=currentTime)) {
+ if (task.period == 0) { // Non-repeating, remove
+ queue.removeMin();
+ task.state = TimerTask.EXECUTED;
+ } else { // Repeating task, reschedule
+ queue.rescheduleMin(
+ task.period<0 ? currentTime - task.period
+ : executionTime + task.period);
+ }
+ }
+ }
+ if (!taskFired) // Task hasn't yet fired; wait
+ queue.wait(executionTime - currentTime);
+ }
+ if (taskFired) // Task fired; run it, holding no locks
+ task.run();
+ } catch(InterruptedException e) {
+ }
+ }
+ }
+}
+
+/**
+ * This class represents a timer task queue: a priority queue of TimerTasks,
+ * ordered on nextExecutionTime. Each Timer object has one of these, which it
+ * shares with its TimerThread. Internally this class uses a heap, which
+ * offers log(n) performance for the add, removeMin and rescheduleMin
+ * operations, and constant time performance for the getMin operation.
+ */
+class TaskQueue {
+ /**
+ * Priority queue represented as a balanced binary heap: the two children
+ * of queue[n] are queue[2*n] and queue[2*n+1]. The priority queue is
+ * ordered on the nextExecutionTime field: The TimerTask with the lowest
+ * nextExecutionTime is in queue[1] (assuming the queue is nonempty). For
+ * each node n in the heap, and each descendant of n, d,
+ * n.nextExecutionTime <= d.nextExecutionTime.
+ */
+ private TimerTask[] queue = new TimerTask[128];
+
+ /**
+ * The number of tasks in the priority queue. (The tasks are stored in
+ * queue[1] up to queue[size]).
+ */
+ private int size = 0;
+
+ /**
+ * Returns the number of tasks currently on the queue.
+ */
+ int size() {
+ return size;
+ }
+
+ /**
+ * Adds a new task to the priority queue.
+ */
+ void add(TimerTask task) {
+ // Grow backing store if necessary
+ if (size + 1 == queue.length)
+ queue = Arrays.copyOf(queue, 2*queue.length);
+
+ queue[++size] = task;
+ fixUp(size);
+ }
+
+ /**
+ * Return the "head task" of the priority queue. (The head task is an
+ * task with the lowest nextExecutionTime.)
+ */
+ TimerTask getMin() {
+ return queue[1];
+ }
+
+ /**
+ * Return the ith task in the priority queue, where i ranges from 1 (the
+ * head task, which is returned by getMin) to the number of tasks on the
+ * queue, inclusive.
+ */
+ TimerTask get(int i) {
+ return queue[i];
+ }
+
+ /**
+ * Remove the head task from the priority queue.
+ */
+ void removeMin() {
+ queue[1] = queue[size];
+ queue[size--] = null; // Drop extra reference to prevent memory leak
+ fixDown(1);
+ }
+
+ /**
+ * Removes the ith element from queue without regard for maintaining
+ * the heap invariant. Recall that queue is one-based, so
+ * 1 <= i <= size.
+ */
+ void quickRemove(int i) {
+ assert i <= size;
+
+ queue[i] = queue[size];
+ queue[size--] = null; // Drop extra ref to prevent memory leak
+ }
+
+ /**
+ * Sets the nextExecutionTime associated with the head task to the
+ * specified value, and adjusts priority queue accordingly.
+ */
+ void rescheduleMin(long newTime) {
+ queue[1].nextExecutionTime = newTime;
+ fixDown(1);
+ }
+
+ /**
+ * Returns true if the priority queue contains no elements.
+ */
+ boolean isEmpty() {
+ return size==0;
+ }
+
+ /**
+ * Removes all elements from the priority queue.
+ */
+ void clear() {
+ // Null out task references to prevent memory leak
+ for (int i=1; i<=size; i++)
+ queue[i] = null;
+
+ size = 0;
+ }
+
+ /**
+ * Establishes the heap invariant (described above) assuming the heap
+ * satisfies the invariant except possibly for the leaf-node indexed by k
+ * (which may have a nextExecutionTime less than its parent's).
+ *
+ * This method functions by "promoting" queue[k] up the hierarchy
+ * (by swapping it with its parent) repeatedly until queue[k]'s
+ * nextExecutionTime is greater than or equal to that of its parent.
+ */
+ private void fixUp(int k) {
+ while (k > 1) {
+ int j = k >> 1;
+ if (queue[j].nextExecutionTime <= queue[k].nextExecutionTime)
+ break;
+ TimerTask tmp = queue[j]; queue[j] = queue[k]; queue[k] = tmp;
+ k = j;
+ }
+ }
+
+ /**
+ * Establishes the heap invariant (described above) in the subtree
+ * rooted at k, which is assumed to satisfy the heap invariant except
+ * possibly for node k itself (which may have a nextExecutionTime greater
+ * than its children's).
+ *
+ * This method functions by "demoting" queue[k] down the hierarchy
+ * (by swapping it with its smaller child) repeatedly until queue[k]'s
+ * nextExecutionTime is less than or equal to those of its children.
+ */
+ private void fixDown(int k) {
+ int j;
+ while ((j = k << 1) <= size && j > 0) {
+ if (j < size &&
+ queue[j].nextExecutionTime > queue[j+1].nextExecutionTime)
+ j++; // j indexes smallest kid
+ if (queue[k].nextExecutionTime <= queue[j].nextExecutionTime)
+ break;
+ TimerTask tmp = queue[j]; queue[j] = queue[k]; queue[k] = tmp;
+ k = j;
+ }
+ }
+
+ /**
+ * Establishes the heap invariant (described above) in the entire tree,
+ * assuming nothing about the order of the elements prior to the call.
+ */
+ void heapify() {
+ for (int i = size/2; i >= 1; i--)
+ fixDown(i);
+ }
+}
Added: trunk/core/src/openjdk/java/java/util/TimerTask.java
===================================================================
--- trunk/core/src/openjdk/java/java/util/TimerTask.java (rev 0)
+++ trunk/core/src/openjdk/java/java/util/TimerTask.java 2007-09-15 21:45:19 UTC (rev 3504)
@@ -0,0 +1,159 @@
+/*
+ * Copyright 1999-2004 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package java.util;
+
+/**
+ * A task that can be scheduled for one-time or repeated execution by a Timer.
+ *
+ * @author Josh Bloch
+ * @version 1.17, 05/05/07
+ * @see Timer
+ * @since 1.3
+ */
+
+public abstract class TimerTask implements Runnable {
+ /**
+ * This object is used to control access to the TimerTask internals.
+ */
+ final Object lock = new Object();
+
+ /**
+ * The state of this task, chosen from the constants below.
+ */
+ int state = VIRGIN;
+
+ /**
+ * This task has not yet been scheduled.
+ */
+ static final int VIRGIN = 0;
+
+ /**
+ * This task is scheduled for execution. If it is a non-repeating task,
+ * it has not yet been executed.
+ */
+ static final int SCHEDULED = 1;
+
+ /**
+ * This non-repeating task has already executed (or is currently
+ * executing) and has not been cancelled.
+ */
+ static final int EXECUTED = 2;
+
+ /**
+ * This task has been cancelled (with a call to TimerTask.cancel).
+ */
+ static final int CANCELLED = 3;
+
+ /**
+ * Next execution time for this task in the format returned by
+ * System.currentTimeMillis, assuming this ...
[truncated message content] |