ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/TimeUnit.java
Revision: 1.2
Committed: Tue May 27 18:14:40 2003 UTC (21 years, 1 month ago) by dl
Branch: MAIN
CVS Tags: JSR166_PRELIMINARY_TEST_RELEASE_1, JSR166_PRERELEASE_0_1
Changes since 1.1: +28 -13 lines
Log Message:
re-check-in initial implementations

File Contents

# User Rev Content
1 dl 1.2 /*
2     * Written by Doug Lea with assistance from members of JCP JSR-166
3     * Expert Group and released to the public domain. Use, modify, and
4     * redistribute this code in any way without acknowledgement.
5     */
6    
7 tim 1.1 package java.util.concurrent;
8    
9     /**
10     * A <tt>TimeUnit</tt> represents time durations at a given unit of
11     * granularity and provides utility methods to convert across units,
12     * and to perform timing and delay operations in these units.
13     * <tt>TimeUnit</tt> is a &quot;featherweight&quot; class.
14     * It does not maintain time information, but only helps organize and
15     * use time representations that may be maintained separately across
16     * various contexts.
17 dl 1.2 * A static method {@link #nanoTime} provides access to a high
18 tim 1.1 * resolution, nanosecond, timer, which can be used to measure elapsed time.
19     *
20     * <p>The <tt>TimeUnit</tt> class cannot be directly instantiated.
21     * Use the {@link #SECONDS}, {@link #MILLISECONDS}, {@link #MICROSECONDS},
22     * and {@link #NANOSECONDS} static instances that provide predefined
23     * units of precision. If you use these frequently, consider
24     * statically importing this class.
25     *
26     * <p>A <tt>TimeUnit</tt> is mainly used to inform blocking methods which
27     * can timeout, how the timeout parameter should be interpreted. For example,
28     * the following code will timeout in 50 milliseconds if the {@link Lock lock}
29     * is not available:
30     * <pre> Lock lock = ...;
31     * if ( lock.tryLock(50L, TimeUnit.MILLISECONDS) ) ...
32     * </pre>
33     * while this code will timeout in 50 seconds:
34     * <pre>
35     * Lock lock = ...;
36     * if ( lock.tryLock(50L, TimeUnit.SECONDS) ) ...
37     * </pre>
38     * Note however, that there is no guarantee that a particular lock, in this
39     * case, will be able to notice the passage of time at the same granularity
40     * as the given <tt>TimeUnit</tt>.
41     *
42     * @since 1.5
43     * @spec JSR-166
44     * @revised $Date: 2003/03/29 02:17:05 $
45     * @editor $Author: dholmes $
46     *
47     * @fixme The previous version created singleton subclass instances. I could
48     * not see any reason to create subclasses instead of just instances.
49     * Neither approach allows creation of your own units.
50     */
51     public final class TimeUnit implements java.io.Serializable {
52    
53     /**
54     * Return the current value of the system high resolution timer, in
55     * nanoseconds. This method can only be used to measure elapsed time
56     * and is not related to any notion of system, or wall-clock time.
57     * Although the value returned represents nanoseconds since some
58     * arbitrary start time in the past, the resolution at which this value
59 dl 1.2 * is updated is not specified. It provides have nanosecond precision, but
60 tim 1.1 * not necessarily nanosecond accuracy.
61     * It is guaranteed that successive return
62     * values from this method will not decrease.
63     *
64     * <p> For example to measure how long some code takes to execute,
65     * with nanosecond precision:
66     * <pre>
67 dl 1.2 * long startTime = TimeUnit.nanoTime();
68 tim 1.1 * // ... the code being measured ...
69 dl 1.2 * long estimatedTime = TimeUnit.nanoTime() - startTime;
70 tim 1.1 * </pre>
71     *
72     * @return The current value of the system high resolution timer, in
73     * nanoseconds.
74     *
75     * @fixme Is this spec tight enough? Too tight? What about issues of
76     * reading the TSC from different processors on a SMP?
77     */
78 dl 1.2 public static final long nanoTime() {
79     return JSR166Support.currentTimeNanos();
80 tim 1.1 }
81    
82     /**
83     * Convert the given time duration in the given unit to the
84     * current unit. Conversions from finer to coarser granulaties
85     * truncate, so lose precision. Conversions from coarser to finer
86     * granularities may numerically overflow.
87     *
88     * @param duration the time duration in the given <tt>unit</tt>
89     * @param unit the unit of the <tt>duration</tt> argument
90     * @return the converted duration in the current unit.
91     */
92     public long convert(long duration, TimeUnit unit) {
93 dl 1.2 if (unit == this)
94     return duration;
95     if (index > unit.index)
96 tim 1.1 return duration / multipliers[index - unit.index];
97 dl 1.2 else
98 tim 1.1 return duration * multipliers[unit.index - index];
99 dl 1.2 }
100    
101     /**
102     * Equivalent to <code>NANOOSECONDS.convert(duration, this)</code>.
103     * @param duration the duration
104     * @return the converted duration.
105     **/
106     public long toNanos(long duration) {
107     if (index == NS)
108     return duration;
109     else
110     return duration * multipliers[index];
111 tim 1.1 }
112    
113     /**
114     * Perform a timed <tt>Object.wait</tt> using the current time unit.
115     * This is a convenience method that converts timeout arguments into the
116     * form required by the <tt>Object.wait</tt> method.
117     * <p>For example, you could implement a blocking <tt>poll</tt> method (see
118     * {@link BlockingQueue#poll BlockingQueue.poll} using:
119     * <pre> public synchronized Object poll(long timeout, TimeUnit unit) throws InterruptedException {
120     * while (empty) {
121     * unit.timedWait(this, timeout);
122     * ...
123     * }
124     * }</pre>
125     * @param obj the object to wait on
126     * @param timeout the maximum time to wait
127     * @throws InterruptedException if interrupted while waiting.
128     * @see Object#wait(long, int)
129     */
130     public void timedWait(Object obj, long timeout)
131     throws InterruptedException {
132     long ms = MILLISECONDS.convert(timeout, this);
133     int ns = excessNanos(timeout, ms);
134     obj.wait(ms, ns);
135     }
136    
137     /**
138     * Perform a timed <tt>Thread.join</tt> using the current time unit.
139     * This is a convenience method that converts time arguments into the
140     * form required by the <tt>Thread.join</tt> method.
141     * @param thread the thread to wait for
142     * @param timeout the maximum time to wait
143     * @throws InterruptedException if interrupted while waiting.
144     * @see Thread#join(long, int)
145     */
146     public void timedJoin(Thread thread, long timeout)
147     throws InterruptedException {
148     long ms = MILLISECONDS.convert(timeout, this);
149     int ns = excessNanos(timeout, ms);
150     thread.join(ms, ns);
151     }
152    
153     /**
154     * Perform a <tt>Thread.sleep</tt> using the current time unit.
155     * This is a convenience method that converts time arguments into the
156     * form required by the <tt>Thread.sleep</tt> method.
157     * @param time the minimum time to sleep
158     * @throws InterruptedException if interrupted while sleeping.
159     * @see Thread#sleep
160     */
161     public void sleep(long timeout) throws InterruptedException {
162     long ms = MILLISECONDS.convert(timeout, this);
163     int ns = excessNanos(timeout, ms);
164     Thread.sleep(ms, ns);
165     }
166    
167     /* ordered indices for each time unit */
168     private static final int NS = 0;
169     private static final int US = 1;
170     private static final int MS = 2;
171     private static final int S = 3;
172    
173     /* quick lookup table for conversion factors */
174     static final int[] multipliers = { 1, 1000, 1000*1000, 1000*1000*1000 };
175    
176     /* the index of this unit */
177     int index;
178    
179     /** private constructor */
180     TimeUnit(int index) { this.index = index; }
181    
182     /**
183     * Utility method to compute the excess-nanosecond argument to
184     * wait, sleep, join.
185     * @fixme overflow?
186     */
187     private int excessNanos(long time, long ms) {
188     if (index == NS)
189     return (int) (time - (ms * multipliers[MS-NS]));
190     else if (index == US)
191     return (int) ((time * multipliers[US-NS]) - (ms * multipliers[MS-NS]));
192     else
193     return 0;
194     }
195    
196     /** Unit for one-second granularities */
197     public static final TimeUnit SECONDS = new TimeUnit(S);
198    
199     /** Unit for one-millisecond granularities */
200     public static final TimeUnit MILLISECONDS = new TimeUnit(MS);
201    
202     /** Unit for one-microsecond granularities */
203     public static final TimeUnit MICROSECONDS = new TimeUnit(US);
204    
205     /** Unit for one-nanosecond granularities */
206     public static final TimeUnit NANOSECONDS = new TimeUnit(NS);
207    
208     }