ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/TimeUnit.java
Revision: 1.50
Committed: Thu Mar 24 11:41:51 2016 UTC (8 years, 2 months ago) by dl
Branch: MAIN
Changes since 1.49: +34 -17 lines
Log Message:
Minor coding tweaks

File Contents

# User Rev Content
1 dl 1.2 /*
2 jsr166 1.35 * Written by Doug Lea with assistance from members of JCP JSR-166
3     * Expert Group and released to the public domain, as explained at
4 jsr166 1.38 * http://creativecommons.org/publicdomain/zero/1.0/
5 jsr166 1.35 */
6 dl 1.2
7 tim 1.1 package java.util.concurrent;
8    
9 jsr166 1.48 import java.time.temporal.ChronoUnit;
10     import java.util.Objects;
11    
12 tim 1.1 /**
13 jsr166 1.40 * A {@code TimeUnit} represents time durations at a given unit of
14 dl 1.27 * granularity and provides utility methods to convert across units,
15     * and to perform timing and delay operations in these units. A
16 jsr166 1.40 * {@code TimeUnit} does not maintain time information, but only
17 dl 1.27 * helps organize and use time representations that may be maintained
18     * separately across various contexts. A nanosecond is defined as one
19     * thousandth of a microsecond, a microsecond as one thousandth of a
20     * millisecond, a millisecond as one thousandth of a second, a minute
21     * as sixty seconds, an hour as sixty minutes, and a day as twenty four
22     * hours.
23     *
24 jsr166 1.40 * <p>A {@code TimeUnit} is mainly used to inform time-based methods
25 dl 1.27 * how a given timing parameter should be interpreted. For example,
26     * the following code will timeout in 50 milliseconds if the {@link
27     * java.util.concurrent.locks.Lock lock} is not available:
28     *
29 jsr166 1.45 * <pre> {@code
30 jsr166 1.39 * Lock lock = ...;
31     * if (lock.tryLock(50L, TimeUnit.MILLISECONDS)) ...}</pre>
32     *
33 dl 1.27 * while this code will timeout in 50 seconds:
34 jsr166 1.45 * <pre> {@code
35 jsr166 1.39 * Lock lock = ...;
36     * if (lock.tryLock(50L, TimeUnit.SECONDS)) ...}</pre>
37 dl 1.27 *
38     * Note however, that there is no guarantee that a particular timeout
39     * implementation will be able to notice the passage of time at the
40 jsr166 1.40 * same granularity as the given {@code TimeUnit}.
41 dl 1.27 *
42     * @since 1.5
43     * @author Doug Lea
44     */
45 dl 1.20 public enum TimeUnit {
46 jsr166 1.43 /**
47 jsr166 1.47 * Time unit representing one thousandth of a microsecond.
48 jsr166 1.43 */
49 dl 1.49 NANOSECONDS(1L), // (cannot use symbolic scale names here)
50 jsr166 1.43 /**
51 jsr166 1.47 * Time unit representing one thousandth of a millisecond.
52 jsr166 1.43 */
53 dl 1.49 MICROSECONDS(1000L),
54 jsr166 1.43 /**
55 jsr166 1.47 * Time unit representing one thousandth of a second.
56 jsr166 1.43 */
57 dl 1.49 MILLISECONDS(1000L * 1000L),
58 jsr166 1.43 /**
59 jsr166 1.47 * Time unit representing one second.
60 jsr166 1.43 */
61 dl 1.49 SECONDS(1000L * 1000L * 1000L),
62 jsr166 1.43 /**
63 jsr166 1.47 * Time unit representing sixty seconds.
64 jsr166 1.44 * @since 1.6
65 jsr166 1.43 */
66 dl 1.49 MINUTES(1000L * 1000L * 1000L * 60L),
67 jsr166 1.43 /**
68 jsr166 1.47 * Time unit representing sixty minutes.
69 jsr166 1.44 * @since 1.6
70 jsr166 1.43 */
71 dl 1.49 HOURS(1000L * 1000L * 1000L * 60L * 60L),
72 jsr166 1.43 /**
73 jsr166 1.47 * Time unit representing twenty four hours.
74 jsr166 1.44 * @since 1.6
75 jsr166 1.43 */
76 dl 1.49 DAYS(1000L * 1000L * 1000L * 60L * 60L * 24L);
77    
78     // Scales as constants
79     private static final long NANO_SCALE = 1L;
80     private static final long MICRO_SCALE = 1000L * NANO_SCALE;
81     private static final long MILLI_SCALE = 1000L * MICRO_SCALE;
82     private static final long SECOND_SCALE = 1000L * MILLI_SCALE;
83     private static final long MINUTE_SCALE = 60L * SECOND_SCALE;
84     private static final long HOUR_SCALE = 60L * MINUTE_SCALE;
85     private static final long DAY_SCALE = 24L * HOUR_SCALE;
86    
87     /*
88     * Instances cache conversion ratios and saturation cutoffs for
89     * the two units commonly used for JDK timing, used in methods
90     * toNanos and toMillis. Other cases compute them, in method cvt.
91     */
92    
93     private final long scale;
94     private final long maxNanos;
95     private final long millisRatio;
96     private final long maxMillis;
97    
98     TimeUnit(long scale) {
99     this.scale = scale;
100     this.maxNanos = Long.MAX_VALUE / scale;
101     long r = (scale >= MILLI_SCALE ? scale / MILLI_SCALE :
102     MILLI_SCALE / scale);
103     this.millisRatio = r;
104     this.maxMillis = Long.MAX_VALUE / r;
105     }
106    
107     /**
108     * General conversion utility.
109     *
110     * @param d duration
111     * @param dst result scale unit
112     * @param src source scale unit
113     */
114     private static long cvt(long d, long dst, long src) {
115     long r, m;
116 dl 1.50 if (src == dst)
117     return d;
118     else if (src < dst)
119     return d / (dst / src);
120     else if (d > (m = Long.MAX_VALUE / (r = src / dst)))
121     return Long.MAX_VALUE;
122     else if (d < -m)
123     return Long.MIN_VALUE;
124     else
125     return d * r;
126 dl 1.49 }
127 dl 1.32
128 dl 1.27 /**
129 jsr166 1.42 * Converts the given time duration in the given unit to this unit.
130     * Conversions from finer to coarser granularities truncate, so
131     * lose precision. For example, converting {@code 999} milliseconds
132     * to seconds results in {@code 0}. Conversions from coarser to
133     * finer granularities with arguments that would numerically
134     * overflow saturate to {@code Long.MIN_VALUE} if negative or
135     * {@code Long.MAX_VALUE} if positive.
136 jsr166 1.33 *
137     * <p>For example, to convert 10 minutes to milliseconds, use:
138 jsr166 1.40 * {@code TimeUnit.MILLISECONDS.convert(10L, TimeUnit.MINUTES)}
139 dl 1.27 *
140 jsr166 1.40 * @param sourceDuration the time duration in the given {@code sourceUnit}
141     * @param sourceUnit the unit of the {@code sourceDuration} argument
142 dl 1.27 * @return the converted duration in this unit,
143 jsr166 1.40 * or {@code Long.MIN_VALUE} if conversion would negatively
144     * overflow, or {@code Long.MAX_VALUE} if it would positively overflow.
145 dl 1.27 */
146 dl 1.32 public long convert(long sourceDuration, TimeUnit sourceUnit) {
147 dl 1.49 return cvt(sourceDuration, scale, sourceUnit.scale);
148 dl 1.32 }
149 jsr166 1.29
150 dl 1.27 /**
151 jsr166 1.41 * Equivalent to
152     * {@link #convert(long, TimeUnit) NANOSECONDS.convert(duration, this)}.
153 dl 1.27 * @param duration the duration
154     * @return the converted duration,
155 jsr166 1.40 * or {@code Long.MIN_VALUE} if conversion would negatively
156     * overflow, or {@code Long.MAX_VALUE} if it would positively overflow.
157 dl 1.27 */
158 dl 1.32 public long toNanos(long duration) {
159 dl 1.49 long s, m;
160 dl 1.50 if ((s = scale) == NANO_SCALE)
161     return duration;
162     else if (duration > (m = maxNanos))
163     return Long.MAX_VALUE;
164     else if (duration < -m)
165     return Long.MIN_VALUE;
166     else
167     return duration * s;
168 dl 1.32 }
169 jsr166 1.29
170 dl 1.27 /**
171 jsr166 1.41 * Equivalent to
172     * {@link #convert(long, TimeUnit) MICROSECONDS.convert(duration, this)}.
173 dl 1.27 * @param duration the duration
174     * @return the converted duration,
175 jsr166 1.40 * or {@code Long.MIN_VALUE} if conversion would negatively
176     * overflow, or {@code Long.MAX_VALUE} if it would positively overflow.
177 dl 1.27 */
178 dl 1.32 public long toMicros(long duration) {
179 dl 1.49 return cvt(duration, MICRO_SCALE, scale);
180 dl 1.32 }
181 jsr166 1.29
182 dl 1.27 /**
183 jsr166 1.41 * Equivalent to
184     * {@link #convert(long, TimeUnit) MILLISECONDS.convert(duration, this)}.
185 dl 1.27 * @param duration the duration
186     * @return the converted duration,
187 jsr166 1.40 * or {@code Long.MIN_VALUE} if conversion would negatively
188     * overflow, or {@code Long.MAX_VALUE} if it would positively overflow.
189 dl 1.27 */
190 dl 1.32 public long toMillis(long duration) {
191 dl 1.49 long s, m;
192 dl 1.50 if ((s = scale) == MILLI_SCALE)
193     return duration;
194     else if (s < MILLI_SCALE)
195     return duration / millisRatio;
196     else if (duration > (m = maxMillis))
197     return Long.MAX_VALUE;
198     else if (duration < -m)
199     return Long.MIN_VALUE;
200     else
201     return duration * millisRatio;
202 dl 1.32 }
203 jsr166 1.29
204 dl 1.27 /**
205 jsr166 1.41 * Equivalent to
206     * {@link #convert(long, TimeUnit) SECONDS.convert(duration, this)}.
207 dl 1.27 * @param duration the duration
208     * @return the converted duration,
209 jsr166 1.40 * or {@code Long.MIN_VALUE} if conversion would negatively
210     * overflow, or {@code Long.MAX_VALUE} if it would positively overflow.
211 dl 1.27 */
212 dl 1.32 public long toSeconds(long duration) {
213 dl 1.49 return cvt(duration, SECOND_SCALE, scale);
214 dl 1.32 }
215 jsr166 1.29
216 dl 1.27 /**
217 jsr166 1.41 * Equivalent to
218     * {@link #convert(long, TimeUnit) MINUTES.convert(duration, this)}.
219 dl 1.27 * @param duration the duration
220     * @return the converted duration,
221 jsr166 1.40 * or {@code Long.MIN_VALUE} if conversion would negatively
222     * overflow, or {@code Long.MAX_VALUE} if it would positively overflow.
223 dl 1.31 * @since 1.6
224 dl 1.27 */
225 dl 1.32 public long toMinutes(long duration) {
226 dl 1.49 return cvt(duration, MINUTE_SCALE, scale);
227 dl 1.32 }
228 jsr166 1.29
229 dl 1.27 /**
230 jsr166 1.41 * Equivalent to
231     * {@link #convert(long, TimeUnit) HOURS.convert(duration, this)}.
232 dl 1.27 * @param duration the duration
233     * @return the converted duration,
234 jsr166 1.40 * or {@code Long.MIN_VALUE} if conversion would negatively
235     * overflow, or {@code Long.MAX_VALUE} if it would positively overflow.
236 dl 1.31 * @since 1.6
237 dl 1.27 */
238 dl 1.32 public long toHours(long duration) {
239 dl 1.49 return cvt(duration, HOUR_SCALE, scale);
240 dl 1.32 }
241 jsr166 1.29
242 dl 1.27 /**
243 jsr166 1.41 * Equivalent to
244     * {@link #convert(long, TimeUnit) DAYS.convert(duration, this)}.
245 dl 1.27 * @param duration the duration
246     * @return the converted duration
247 dl 1.31 * @since 1.6
248 dl 1.27 */
249 dl 1.32 public long toDays(long duration) {
250 dl 1.49 return cvt(duration, DAY_SCALE, scale);
251 dl 1.32 }
252 jsr166 1.29
253 dl 1.27 /**
254     * Utility to compute the excess-nanosecond argument to wait,
255     * sleep, join.
256     * @param d the duration
257     * @param m the number of milliseconds
258     * @return the number of nanoseconds
259     */
260 dl 1.49 private int excessNanos(long d, long m) {
261     long s;
262 dl 1.50 if ((s = scale) == NANO_SCALE)
263     return (int)(d - (m * MILLI_SCALE));
264     else if (s == MICRO_SCALE)
265     return (int)((d * 1000L) - (m * MILLI_SCALE));
266     else
267     return 0;
268 dl 1.49 }
269 jsr166 1.29
270 dl 1.27 /**
271 jsr166 1.37 * Performs a timed {@link Object#wait(long, int) Object.wait}
272     * using this time unit.
273 dl 1.27 * This is a convenience method that converts timeout arguments
274 jsr166 1.40 * into the form required by the {@code Object.wait} method.
275 dl 1.27 *
276 jsr166 1.40 * <p>For example, you could implement a blocking {@code poll}
277 dl 1.27 * method (see {@link BlockingQueue#poll BlockingQueue.poll})
278     * using:
279     *
280 jsr166 1.45 * <pre> {@code
281 jsr166 1.36 * public synchronized Object poll(long timeout, TimeUnit unit)
282     * throws InterruptedException {
283     * while (empty) {
284     * unit.timedWait(this, timeout);
285     * ...
286     * }
287     * }}</pre>
288 dl 1.27 *
289     * @param obj the object to wait on
290 dl 1.28 * @param timeout the maximum time to wait. If less than
291     * or equal to zero, do not wait at all.
292 jsr166 1.37 * @throws InterruptedException if interrupted while waiting
293 dl 1.27 */
294     public void timedWait(Object obj, long timeout)
295 jsr166 1.37 throws InterruptedException {
296 dl 1.27 if (timeout > 0) {
297     long ms = toMillis(timeout);
298     int ns = excessNanos(timeout, ms);
299     obj.wait(ms, ns);
300     }
301     }
302 jsr166 1.29
303 dl 1.27 /**
304 jsr166 1.37 * Performs a timed {@link Thread#join(long, int) Thread.join}
305     * using this time unit.
306 dl 1.27 * This is a convenience method that converts time arguments into the
307 jsr166 1.40 * form required by the {@code Thread.join} method.
308 jsr166 1.37 *
309 dl 1.27 * @param thread the thread to wait for
310 dl 1.28 * @param timeout the maximum time to wait. If less than
311     * or equal to zero, do not wait at all.
312 jsr166 1.37 * @throws InterruptedException if interrupted while waiting
313 dl 1.27 */
314     public void timedJoin(Thread thread, long timeout)
315 jsr166 1.37 throws InterruptedException {
316 dl 1.27 if (timeout > 0) {
317     long ms = toMillis(timeout);
318     int ns = excessNanos(timeout, ms);
319     thread.join(ms, ns);
320     }
321     }
322 jsr166 1.29
323 dl 1.27 /**
324 jsr166 1.37 * Performs a {@link Thread#sleep(long, int) Thread.sleep} using
325     * this time unit.
326 dl 1.27 * This is a convenience method that converts time arguments into the
327 jsr166 1.40 * form required by the {@code Thread.sleep} method.
328 jsr166 1.37 *
329 dl 1.28 * @param timeout the minimum time to sleep. If less than
330     * or equal to zero, do not sleep at all.
331 jsr166 1.37 * @throws InterruptedException if interrupted while sleeping
332 dl 1.27 */
333     public void sleep(long timeout) throws InterruptedException {
334     if (timeout > 0) {
335     long ms = toMillis(timeout);
336     int ns = excessNanos(timeout, ms);
337     Thread.sleep(ms, ns);
338     }
339     }
340 jsr166 1.29
341 jsr166 1.48 /**
342     * Converts this {@code TimeUnit} to the equivalent {@code ChronoUnit}.
343     *
344     * @return the converted equivalent ChronoUnit
345     * @since 9
346     */
347     public ChronoUnit toChronoUnit() {
348     switch (this) {
349     case NANOSECONDS: return ChronoUnit.NANOS;
350     case MICROSECONDS: return ChronoUnit.MICROS;
351     case MILLISECONDS: return ChronoUnit.MILLIS;
352     case SECONDS: return ChronoUnit.SECONDS;
353     case MINUTES: return ChronoUnit.MINUTES;
354     case HOURS: return ChronoUnit.HOURS;
355     case DAYS: return ChronoUnit.DAYS;
356     default: throw new AssertionError();
357     }
358     }
359    
360     /**
361     * Converts a {@code ChronoUnit} to the equivalent {@code TimeUnit}.
362     *
363     * @param chronoUnit the ChronoUnit to convert
364     * @return the converted equivalent TimeUnit
365     * @throws IllegalArgumentException if {@code chronoUnit} has no
366     * equivalent TimeUnit
367     * @throws NullPointerException if {@code chronoUnit} is null
368     * @since 9
369     */
370     public static TimeUnit of(ChronoUnit chronoUnit) {
371     switch (Objects.requireNonNull(chronoUnit, "chronoUnit")) {
372     case NANOS: return TimeUnit.NANOSECONDS;
373     case MICROS: return TimeUnit.MICROSECONDS;
374     case MILLIS: return TimeUnit.MILLISECONDS;
375     case SECONDS: return TimeUnit.SECONDS;
376     case MINUTES: return TimeUnit.MINUTES;
377     case HOURS: return TimeUnit.HOURS;
378     case DAYS: return TimeUnit.DAYS;
379     default:
380     throw new IllegalArgumentException(
381     "No TimeUnit equivalent for " + chronoUnit);
382     }
383     }
384    
385 tim 1.1 }