ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jdk8/java/util/concurrent/TimeUnit.java
Revision: 1.5
Committed: Fri Jun 8 02:20:22 2018 UTC (5 years, 11 months ago) by jsr166
Branch: MAIN
CVS Tags: HEAD
Changes since 1.4: +59 -18 lines
Log Message:
sync from src/main

File Contents

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