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