ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/TimeUnit.java
Revision: 1.58
Committed: Sat Mar 26 17:05:48 2016 UTC (8 years, 2 months ago) by jsr166
Branch: MAIN
Changes since 1.57: +14 -14 lines
Log Message:
very small readability improvement

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 jsr166 1.56 NANOSECONDS(TimeUnit.NANO_SCALE),
50 jsr166 1.43 /**
51 jsr166 1.47 * Time unit representing one thousandth of a millisecond.
52 jsr166 1.43 */
53 jsr166 1.56 MICROSECONDS(TimeUnit.MICRO_SCALE),
54 jsr166 1.43 /**
55 jsr166 1.47 * Time unit representing one thousandth of a second.
56 jsr166 1.43 */
57 jsr166 1.56 MILLISECONDS(TimeUnit.MILLI_SCALE),
58 jsr166 1.43 /**
59 jsr166 1.47 * Time unit representing one second.
60 jsr166 1.43 */
61 jsr166 1.56 SECONDS(TimeUnit.SECOND_SCALE),
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 jsr166 1.56 MINUTES(TimeUnit.MINUTE_SCALE),
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 jsr166 1.56 HOURS(TimeUnit.HOUR_SCALE),
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 jsr166 1.56 DAYS(TimeUnit.DAY_SCALE);
77 dl 1.49
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 dl 1.53 * the units up through SECONDS. Other cases compute them, in
90 dl 1.52 * method cvt.
91 dl 1.49 */
92    
93     private final long scale;
94     private final long maxNanos;
95 dl 1.53 private final long maxMicros;
96 dl 1.49 private final long maxMillis;
97 dl 1.52 private final long maxSecs;
98 dl 1.53 private final long microRatio;
99     private final int milliRatio; // fits in 32 bits
100     private final int secRatio; // fits in 32 bits
101    
102     TimeUnit(long s) {
103     this.scale = s;
104     this.maxNanos = Long.MAX_VALUE / s;
105     long ur = (s >= MICRO_SCALE) ? (s / MICRO_SCALE) : (MICRO_SCALE / s);
106     this.microRatio = ur;
107     this.maxMicros = Long.MAX_VALUE / ur;
108 jsr166 1.55 long mr = (s >= MILLI_SCALE) ? (s / MILLI_SCALE) : (MILLI_SCALE / s);
109 dl 1.52 this.milliRatio = (int)mr;
110     this.maxMillis = Long.MAX_VALUE / mr;
111 dl 1.53 long sr = (s >= SECOND_SCALE) ? (s / SECOND_SCALE) : (SECOND_SCALE / s);
112 dl 1.52 this.secRatio = (int)sr;
113     this.maxSecs = Long.MAX_VALUE / sr;
114 dl 1.49 }
115    
116     /**
117     * General conversion utility.
118     *
119     * @param d duration
120 jsr166 1.57 * @param dst result unit scale
121     * @param src source unit scale
122 dl 1.49 */
123     private static long cvt(long d, long dst, long src) {
124     long r, m;
125 dl 1.50 if (src == dst)
126     return d;
127     else if (src < dst)
128     return d / (dst / src);
129     else if (d > (m = Long.MAX_VALUE / (r = src / dst)))
130     return Long.MAX_VALUE;
131     else if (d < -m)
132     return Long.MIN_VALUE;
133     else
134     return d * r;
135 dl 1.49 }
136 dl 1.32
137 dl 1.27 /**
138 jsr166 1.42 * Converts the given time duration in the given unit to this unit.
139     * Conversions from finer to coarser granularities truncate, so
140     * lose precision. For example, converting {@code 999} milliseconds
141     * to seconds results in {@code 0}. Conversions from coarser to
142     * finer granularities with arguments that would numerically
143     * overflow saturate to {@code Long.MIN_VALUE} if negative or
144     * {@code Long.MAX_VALUE} if positive.
145 jsr166 1.33 *
146     * <p>For example, to convert 10 minutes to milliseconds, use:
147 jsr166 1.40 * {@code TimeUnit.MILLISECONDS.convert(10L, TimeUnit.MINUTES)}
148 dl 1.27 *
149 jsr166 1.40 * @param sourceDuration the time duration in the given {@code sourceUnit}
150     * @param sourceUnit the unit of the {@code sourceDuration} argument
151 dl 1.27 * @return the converted duration in this unit,
152 jsr166 1.58 * or {@code Long.MIN_VALUE} if conversion would negatively overflow,
153     * or {@code Long.MAX_VALUE} if it would positively overflow.
154 dl 1.27 */
155 dl 1.32 public long convert(long sourceDuration, TimeUnit sourceUnit) {
156 dl 1.53 switch (this) {
157 jsr166 1.54 case NANOSECONDS: return sourceUnit.toNanos(sourceDuration);
158 dl 1.53 case MICROSECONDS: return sourceUnit.toMicros(sourceDuration);
159     case MILLISECONDS: return sourceUnit.toMillis(sourceDuration);
160 jsr166 1.54 case SECONDS: return sourceUnit.toSeconds(sourceDuration);
161 dl 1.53 default: return cvt(sourceDuration, scale, sourceUnit.scale);
162     }
163 dl 1.32 }
164 jsr166 1.29
165 dl 1.27 /**
166 jsr166 1.41 * Equivalent to
167     * {@link #convert(long, TimeUnit) NANOSECONDS.convert(duration, this)}.
168 dl 1.27 * @param duration the duration
169     * @return the converted duration,
170 jsr166 1.58 * or {@code Long.MIN_VALUE} if conversion would negatively overflow,
171     * or {@code Long.MAX_VALUE} if it would positively overflow.
172 dl 1.27 */
173 dl 1.32 public long toNanos(long duration) {
174 dl 1.49 long s, m;
175 dl 1.50 if ((s = scale) == NANO_SCALE)
176     return duration;
177     else if (duration > (m = maxNanos))
178     return Long.MAX_VALUE;
179     else if (duration < -m)
180     return Long.MIN_VALUE;
181     else
182     return duration * s;
183 dl 1.32 }
184 jsr166 1.29
185 dl 1.27 /**
186 jsr166 1.41 * Equivalent to
187     * {@link #convert(long, TimeUnit) MICROSECONDS.convert(duration, this)}.
188 dl 1.27 * @param duration the duration
189     * @return the converted duration,
190 jsr166 1.58 * or {@code Long.MIN_VALUE} if conversion would negatively overflow,
191     * or {@code Long.MAX_VALUE} if it would positively overflow.
192 dl 1.27 */
193 dl 1.32 public long toMicros(long duration) {
194 dl 1.53 long s, m;
195     if ((s = scale) == MICRO_SCALE)
196     return duration;
197     else if (s < MICRO_SCALE)
198     return duration / microRatio;
199     else if (duration > (m = maxMicros))
200     return Long.MAX_VALUE;
201     else if (duration < -m)
202     return Long.MIN_VALUE;
203     else
204     return duration * microRatio;
205 dl 1.32 }
206 jsr166 1.29
207 dl 1.27 /**
208 jsr166 1.41 * Equivalent to
209     * {@link #convert(long, TimeUnit) MILLISECONDS.convert(duration, this)}.
210 dl 1.27 * @param duration the duration
211     * @return the converted duration,
212 jsr166 1.58 * or {@code Long.MIN_VALUE} if conversion would negatively overflow,
213     * or {@code Long.MAX_VALUE} if it would positively overflow.
214 dl 1.27 */
215 dl 1.32 public long toMillis(long duration) {
216 dl 1.49 long s, m;
217 dl 1.50 if ((s = scale) == MILLI_SCALE)
218     return duration;
219     else if (s < MILLI_SCALE)
220 dl 1.52 return duration / milliRatio;
221 dl 1.50 else if (duration > (m = maxMillis))
222     return Long.MAX_VALUE;
223     else if (duration < -m)
224     return Long.MIN_VALUE;
225     else
226 dl 1.52 return duration * milliRatio;
227 dl 1.32 }
228 jsr166 1.29
229 dl 1.27 /**
230 jsr166 1.41 * Equivalent to
231     * {@link #convert(long, TimeUnit) SECONDS.convert(duration, this)}.
232 dl 1.27 * @param duration the duration
233     * @return the converted duration,
234 jsr166 1.58 * or {@code Long.MIN_VALUE} if conversion would negatively overflow,
235     * or {@code Long.MAX_VALUE} if it would positively overflow.
236 dl 1.27 */
237 dl 1.32 public long toSeconds(long duration) {
238 dl 1.52 long s, m;
239     if ((s = scale) == SECOND_SCALE)
240     return duration;
241     else if (s < SECOND_SCALE)
242     return duration / secRatio;
243     else if (duration > (m = maxSecs))
244     return Long.MAX_VALUE;
245     else if (duration < -m)
246     return Long.MIN_VALUE;
247     else
248     return duration * secRatio;
249 dl 1.32 }
250 jsr166 1.29
251 dl 1.27 /**
252 jsr166 1.41 * Equivalent to
253     * {@link #convert(long, TimeUnit) MINUTES.convert(duration, this)}.
254 dl 1.27 * @param duration the duration
255     * @return the converted duration,
256 jsr166 1.58 * or {@code Long.MIN_VALUE} if conversion would negatively overflow,
257     * or {@code Long.MAX_VALUE} if it would positively overflow.
258 dl 1.31 * @since 1.6
259 dl 1.27 */
260 dl 1.32 public long toMinutes(long duration) {
261 dl 1.49 return cvt(duration, MINUTE_SCALE, scale);
262 dl 1.32 }
263 jsr166 1.29
264 dl 1.27 /**
265 jsr166 1.41 * Equivalent to
266     * {@link #convert(long, TimeUnit) HOURS.convert(duration, this)}.
267 dl 1.27 * @param duration the duration
268     * @return the converted duration,
269 jsr166 1.58 * or {@code Long.MIN_VALUE} if conversion would negatively overflow,
270     * or {@code Long.MAX_VALUE} if it would positively overflow.
271 dl 1.31 * @since 1.6
272 dl 1.27 */
273 dl 1.32 public long toHours(long duration) {
274 dl 1.49 return cvt(duration, HOUR_SCALE, scale);
275 dl 1.32 }
276 jsr166 1.29
277 dl 1.27 /**
278 jsr166 1.41 * Equivalent to
279     * {@link #convert(long, TimeUnit) DAYS.convert(duration, this)}.
280 dl 1.27 * @param duration the duration
281     * @return the converted duration
282 dl 1.31 * @since 1.6
283 dl 1.27 */
284 dl 1.32 public long toDays(long duration) {
285 dl 1.49 return cvt(duration, DAY_SCALE, scale);
286 dl 1.32 }
287 jsr166 1.29
288 dl 1.27 /**
289     * Utility to compute the excess-nanosecond argument to wait,
290     * sleep, join.
291     * @param d the duration
292     * @param m the number of milliseconds
293     * @return the number of nanoseconds
294     */
295 dl 1.49 private int excessNanos(long d, long m) {
296     long s;
297 dl 1.50 if ((s = scale) == NANO_SCALE)
298     return (int)(d - (m * MILLI_SCALE));
299     else if (s == MICRO_SCALE)
300     return (int)((d * 1000L) - (m * MILLI_SCALE));
301     else
302     return 0;
303 dl 1.49 }
304 jsr166 1.29
305 dl 1.27 /**
306 jsr166 1.37 * Performs a timed {@link Object#wait(long, int) Object.wait}
307     * using this time unit.
308 dl 1.27 * This is a convenience method that converts timeout arguments
309 jsr166 1.40 * into the form required by the {@code Object.wait} method.
310 dl 1.27 *
311 jsr166 1.40 * <p>For example, you could implement a blocking {@code poll}
312 dl 1.27 * method (see {@link BlockingQueue#poll BlockingQueue.poll})
313     * using:
314     *
315 jsr166 1.45 * <pre> {@code
316 jsr166 1.36 * public synchronized Object poll(long timeout, TimeUnit unit)
317     * throws InterruptedException {
318     * while (empty) {
319     * unit.timedWait(this, timeout);
320     * ...
321     * }
322     * }}</pre>
323 dl 1.27 *
324     * @param obj the object to wait on
325 dl 1.28 * @param timeout the maximum time to wait. If less than
326     * or equal to zero, do not wait at all.
327 jsr166 1.37 * @throws InterruptedException if interrupted while waiting
328 dl 1.27 */
329     public void timedWait(Object obj, long timeout)
330 jsr166 1.37 throws InterruptedException {
331 dl 1.27 if (timeout > 0) {
332     long ms = toMillis(timeout);
333     int ns = excessNanos(timeout, ms);
334     obj.wait(ms, ns);
335     }
336     }
337 jsr166 1.29
338 dl 1.27 /**
339 jsr166 1.37 * Performs a timed {@link Thread#join(long, int) Thread.join}
340     * using this time unit.
341 dl 1.27 * This is a convenience method that converts time arguments into the
342 jsr166 1.40 * form required by the {@code Thread.join} method.
343 jsr166 1.37 *
344 dl 1.27 * @param thread the thread to wait for
345 dl 1.28 * @param timeout the maximum time to wait. If less than
346     * or equal to zero, do not wait at all.
347 jsr166 1.37 * @throws InterruptedException if interrupted while waiting
348 dl 1.27 */
349     public void timedJoin(Thread thread, long timeout)
350 jsr166 1.37 throws InterruptedException {
351 dl 1.27 if (timeout > 0) {
352     long ms = toMillis(timeout);
353     int ns = excessNanos(timeout, ms);
354     thread.join(ms, ns);
355     }
356     }
357 jsr166 1.29
358 dl 1.27 /**
359 jsr166 1.37 * Performs a {@link Thread#sleep(long, int) Thread.sleep} using
360     * this time unit.
361 dl 1.27 * This is a convenience method that converts time arguments into the
362 jsr166 1.40 * form required by the {@code Thread.sleep} method.
363 jsr166 1.37 *
364 dl 1.28 * @param timeout the minimum time to sleep. If less than
365     * or equal to zero, do not sleep at all.
366 jsr166 1.37 * @throws InterruptedException if interrupted while sleeping
367 dl 1.27 */
368     public void sleep(long timeout) throws InterruptedException {
369     if (timeout > 0) {
370     long ms = toMillis(timeout);
371     int ns = excessNanos(timeout, ms);
372     Thread.sleep(ms, ns);
373     }
374     }
375 jsr166 1.29
376 jsr166 1.48 /**
377     * Converts this {@code TimeUnit} to the equivalent {@code ChronoUnit}.
378     *
379     * @return the converted equivalent ChronoUnit
380     * @since 9
381     */
382     public ChronoUnit toChronoUnit() {
383     switch (this) {
384     case NANOSECONDS: return ChronoUnit.NANOS;
385     case MICROSECONDS: return ChronoUnit.MICROS;
386     case MILLISECONDS: return ChronoUnit.MILLIS;
387     case SECONDS: return ChronoUnit.SECONDS;
388     case MINUTES: return ChronoUnit.MINUTES;
389     case HOURS: return ChronoUnit.HOURS;
390     case DAYS: return ChronoUnit.DAYS;
391     default: throw new AssertionError();
392     }
393     }
394    
395     /**
396     * Converts a {@code ChronoUnit} to the equivalent {@code TimeUnit}.
397     *
398     * @param chronoUnit the ChronoUnit to convert
399     * @return the converted equivalent TimeUnit
400     * @throws IllegalArgumentException if {@code chronoUnit} has no
401     * equivalent TimeUnit
402     * @throws NullPointerException if {@code chronoUnit} is null
403     * @since 9
404     */
405     public static TimeUnit of(ChronoUnit chronoUnit) {
406     switch (Objects.requireNonNull(chronoUnit, "chronoUnit")) {
407     case NANOS: return TimeUnit.NANOSECONDS;
408     case MICROS: return TimeUnit.MICROSECONDS;
409     case MILLIS: return TimeUnit.MILLISECONDS;
410     case SECONDS: return TimeUnit.SECONDS;
411     case MINUTES: return TimeUnit.MINUTES;
412     case HOURS: return TimeUnit.HOURS;
413     case DAYS: return TimeUnit.DAYS;
414     default:
415     throw new IllegalArgumentException(
416     "No TimeUnit equivalent for " + chronoUnit);
417     }
418     }
419    
420 tim 1.1 }