ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/TimeUnit.java
Revision: 1.67
Committed: Fri Jun 22 17:45:03 2018 UTC (5 years, 10 months ago) by jsr166
Branch: MAIN
CVS Tags: HEAD
Changes since 1.66: +3 -2 lines
Log Message:
TimeUnit#convert(Duration): use @apiNote

File Contents

# Content
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 import java.time.Duration;
10 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 NANOSECONDS(TimeUnit.NANO_SCALE),
51 /**
52 * Time unit representing one thousandth of a millisecond.
53 */
54 MICROSECONDS(TimeUnit.MICRO_SCALE),
55 /**
56 * Time unit representing one thousandth of a second.
57 */
58 MILLISECONDS(TimeUnit.MILLI_SCALE),
59 /**
60 * Time unit representing one second.
61 */
62 SECONDS(TimeUnit.SECOND_SCALE),
63 /**
64 * Time unit representing sixty seconds.
65 * @since 1.6
66 */
67 MINUTES(TimeUnit.MINUTE_SCALE),
68 /**
69 * Time unit representing sixty minutes.
70 * @since 1.6
71 */
72 HOURS(TimeUnit.HOUR_SCALE),
73 /**
74 * Time unit representing twenty four hours.
75 * @since 1.6
76 */
77 DAYS(TimeUnit.DAY_SCALE);
78
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 * the units up through SECONDS. Other cases compute them, in
91 * method cvt.
92 */
93
94 private final long scale;
95 private final long maxNanos;
96 private final long maxMicros;
97 private final long maxMillis;
98 private final long maxSecs;
99 private final long microRatio;
100 private final int milliRatio; // fits in 32 bits
101 private final int secRatio; // fits in 32 bits
102
103 private TimeUnit(long s) {
104 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 long mr = (s >= MILLI_SCALE) ? (s / MILLI_SCALE) : (MILLI_SCALE / s);
110 this.milliRatio = (int)mr;
111 this.maxMillis = Long.MAX_VALUE / mr;
112 long sr = (s >= SECOND_SCALE) ? (s / SECOND_SCALE) : (SECOND_SCALE / s);
113 this.secRatio = (int)sr;
114 this.maxSecs = Long.MAX_VALUE / sr;
115 }
116
117 /**
118 * General conversion utility.
119 *
120 * @param d duration
121 * @param dst result unit scale
122 * @param src source unit scale
123 */
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 * or {@code Long.MIN_VALUE} if conversion would negatively overflow,
154 * or {@code Long.MAX_VALUE} if it would positively overflow.
155 */
156 public long convert(long sourceDuration, TimeUnit sourceUnit) {
157 switch (this) {
158 case NANOSECONDS: return sourceUnit.toNanos(sourceDuration);
159 case MICROSECONDS: return sourceUnit.toMicros(sourceDuration);
160 case MILLISECONDS: return sourceUnit.toMillis(sourceDuration);
161 case SECONDS: return sourceUnit.toSeconds(sourceDuration);
162 default: return cvt(sourceDuration, scale, sourceUnit.scale);
163 }
164 }
165
166 /**
167 * 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 * @apiNote
177 * This method differs from {@link Duration#toNanos()} in that it
178 * does not throw {@link ArithmeticException} on numeric overflow.
179 *
180 * @param duration the time duration
181 * @return the converted duration in this unit,
182 * or {@code Long.MIN_VALUE} if conversion would negatively overflow,
183 * or {@code Long.MAX_VALUE} if it would positively overflow.
184 * @throws NullPointerException if {@code duration} is null
185 * @see Duration#of(long,TemporalUnit)
186 * @since 11
187 */
188 public long convert(Duration duration) {
189 long secs = duration.getSeconds();
190 int nano = duration.getNano();
191 if (secs < 0 && nano > 0) {
192 // use representation compatible with integer division
193 secs++;
194 nano -= (int) SECOND_SCALE;
195 }
196 final long s, nanoVal;
197 // Optimize for the common case - NANOSECONDS without overflow
198 if (this == NANOSECONDS)
199 nanoVal = nano;
200 else if ((s = scale) < SECOND_SCALE)
201 nanoVal = nano / s;
202 else if (this == SECONDS)
203 return secs;
204 else
205 return secs / secRatio;
206 long val = secs * secRatio + nanoVal;
207 return ((secs < maxSecs && secs > -maxSecs) ||
208 (secs == maxSecs && val > 0) ||
209 (secs == -maxSecs && val < 0))
210 ? val
211 : (secs > 0) ? Long.MAX_VALUE : Long.MIN_VALUE;
212 }
213
214 /**
215 * Equivalent to
216 * {@link #convert(long, TimeUnit) NANOSECONDS.convert(duration, this)}.
217 * @param duration the duration
218 * @return the converted duration,
219 * or {@code Long.MIN_VALUE} if conversion would negatively overflow,
220 * or {@code Long.MAX_VALUE} if it would positively overflow.
221 */
222 public long toNanos(long duration) {
223 long s, m;
224 if ((s = scale) == NANO_SCALE)
225 return duration;
226 else if (duration > (m = maxNanos))
227 return Long.MAX_VALUE;
228 else if (duration < -m)
229 return Long.MIN_VALUE;
230 else
231 return duration * s;
232 }
233
234 /**
235 * Equivalent to
236 * {@link #convert(long, TimeUnit) MICROSECONDS.convert(duration, this)}.
237 * @param duration the duration
238 * @return the converted duration,
239 * or {@code Long.MIN_VALUE} if conversion would negatively overflow,
240 * or {@code Long.MAX_VALUE} if it would positively overflow.
241 */
242 public long toMicros(long duration) {
243 long s, m;
244 if ((s = scale) <= MICRO_SCALE)
245 return (s == MICRO_SCALE) ? duration : duration / microRatio;
246 else if (duration > (m = maxMicros))
247 return Long.MAX_VALUE;
248 else if (duration < -m)
249 return Long.MIN_VALUE;
250 else
251 return duration * microRatio;
252 }
253
254 /**
255 * Equivalent to
256 * {@link #convert(long, TimeUnit) MILLISECONDS.convert(duration, this)}.
257 * @param duration the duration
258 * @return the converted duration,
259 * or {@code Long.MIN_VALUE} if conversion would negatively overflow,
260 * or {@code Long.MAX_VALUE} if it would positively overflow.
261 */
262 public long toMillis(long duration) {
263 long s, m;
264 if ((s = scale) <= MILLI_SCALE)
265 return (s == MILLI_SCALE) ? duration : duration / milliRatio;
266 else if (duration > (m = maxMillis))
267 return Long.MAX_VALUE;
268 else if (duration < -m)
269 return Long.MIN_VALUE;
270 else
271 return duration * milliRatio;
272 }
273
274 /**
275 * Equivalent to
276 * {@link #convert(long, TimeUnit) SECONDS.convert(duration, this)}.
277 * @param duration the duration
278 * @return the converted duration,
279 * or {@code Long.MIN_VALUE} if conversion would negatively overflow,
280 * or {@code Long.MAX_VALUE} if it would positively overflow.
281 */
282 public long toSeconds(long duration) {
283 long s, m;
284 if ((s = scale) <= SECOND_SCALE)
285 return (s == SECOND_SCALE) ? duration : duration / secRatio;
286 else if (duration > (m = maxSecs))
287 return Long.MAX_VALUE;
288 else if (duration < -m)
289 return Long.MIN_VALUE;
290 else
291 return duration * secRatio;
292 }
293
294 /**
295 * Equivalent to
296 * {@link #convert(long, TimeUnit) MINUTES.convert(duration, this)}.
297 * @param duration the duration
298 * @return the converted duration,
299 * or {@code Long.MIN_VALUE} if conversion would negatively overflow,
300 * or {@code Long.MAX_VALUE} if it would positively overflow.
301 * @since 1.6
302 */
303 public long toMinutes(long duration) {
304 return cvt(duration, MINUTE_SCALE, scale);
305 }
306
307 /**
308 * Equivalent to
309 * {@link #convert(long, TimeUnit) HOURS.convert(duration, this)}.
310 * @param duration the duration
311 * @return the converted duration,
312 * or {@code Long.MIN_VALUE} if conversion would negatively overflow,
313 * or {@code Long.MAX_VALUE} if it would positively overflow.
314 * @since 1.6
315 */
316 public long toHours(long duration) {
317 return cvt(duration, HOUR_SCALE, scale);
318 }
319
320 /**
321 * Equivalent to
322 * {@link #convert(long, TimeUnit) DAYS.convert(duration, this)}.
323 * @param duration the duration
324 * @return the converted duration
325 * @since 1.6
326 */
327 public long toDays(long duration) {
328 return cvt(duration, DAY_SCALE, scale);
329 }
330
331 /**
332 * Utility to compute the excess-nanosecond argument to wait,
333 * sleep, join.
334 * @param d the duration
335 * @param m the number of milliseconds
336 * @return the number of nanoseconds
337 */
338 private int excessNanos(long d, long m) {
339 long s;
340 if ((s = scale) == NANO_SCALE)
341 return (int)(d - (m * MILLI_SCALE));
342 else if (s == MICRO_SCALE)
343 return (int)((d * 1000L) - (m * MILLI_SCALE));
344 else
345 return 0;
346 }
347
348 /**
349 * Performs a timed {@link Object#wait(long, int) Object.wait}
350 * using this time unit.
351 * This is a convenience method that converts timeout arguments
352 * into the form required by the {@code Object.wait} method.
353 *
354 * <p>For example, you could implement a blocking {@code poll} method
355 * (see {@link BlockingQueue#poll(long, TimeUnit) BlockingQueue.poll})
356 * using:
357 *
358 * <pre> {@code
359 * public E poll(long timeout, TimeUnit unit)
360 * throws InterruptedException {
361 * synchronized (lock) {
362 * while (isEmpty()) {
363 * unit.timedWait(lock, timeout);
364 * ...
365 * }
366 * }
367 * }}</pre>
368 *
369 * @param obj the object to wait on
370 * @param timeout the maximum time to wait. If less than
371 * or equal to zero, do not wait at all.
372 * @throws InterruptedException if interrupted while waiting
373 */
374 public void timedWait(Object obj, long timeout)
375 throws InterruptedException {
376 if (timeout > 0) {
377 long ms = toMillis(timeout);
378 int ns = excessNanos(timeout, ms);
379 obj.wait(ms, ns);
380 }
381 }
382
383 /**
384 * Performs a timed {@link Thread#join(long, int) Thread.join}
385 * using this time unit.
386 * This is a convenience method that converts time arguments into the
387 * form required by the {@code Thread.join} method.
388 *
389 * @param thread the thread to wait for
390 * @param timeout the maximum time to wait. If less than
391 * or equal to zero, do not wait at all.
392 * @throws InterruptedException if interrupted while waiting
393 */
394 public void timedJoin(Thread thread, long timeout)
395 throws InterruptedException {
396 if (timeout > 0) {
397 long ms = toMillis(timeout);
398 int ns = excessNanos(timeout, ms);
399 thread.join(ms, ns);
400 }
401 }
402
403 /**
404 * Performs a {@link Thread#sleep(long, int) Thread.sleep} using
405 * this time unit.
406 * This is a convenience method that converts time arguments into the
407 * form required by the {@code Thread.sleep} method.
408 *
409 * @param timeout the minimum time to sleep. If less than
410 * or equal to zero, do not sleep at all.
411 * @throws InterruptedException if interrupted while sleeping
412 */
413 public void sleep(long timeout) throws InterruptedException {
414 if (timeout > 0) {
415 long ms = toMillis(timeout);
416 int ns = excessNanos(timeout, ms);
417 Thread.sleep(ms, ns);
418 }
419 }
420
421 /**
422 * Converts this {@code TimeUnit} to the equivalent {@code ChronoUnit}.
423 *
424 * @return the converted equivalent ChronoUnit
425 * @since 9
426 */
427 public ChronoUnit toChronoUnit() {
428 switch (this) {
429 case NANOSECONDS: return ChronoUnit.NANOS;
430 case MICROSECONDS: return ChronoUnit.MICROS;
431 case MILLISECONDS: return ChronoUnit.MILLIS;
432 case SECONDS: return ChronoUnit.SECONDS;
433 case MINUTES: return ChronoUnit.MINUTES;
434 case HOURS: return ChronoUnit.HOURS;
435 case DAYS: return ChronoUnit.DAYS;
436 default: throw new AssertionError();
437 }
438 }
439
440 /**
441 * Converts a {@code ChronoUnit} to the equivalent {@code TimeUnit}.
442 *
443 * @param chronoUnit the ChronoUnit to convert
444 * @return the converted equivalent TimeUnit
445 * @throws IllegalArgumentException if {@code chronoUnit} has no
446 * equivalent TimeUnit
447 * @throws NullPointerException if {@code chronoUnit} is null
448 * @since 9
449 */
450 public static TimeUnit of(ChronoUnit chronoUnit) {
451 switch (Objects.requireNonNull(chronoUnit, "chronoUnit")) {
452 case NANOS: return TimeUnit.NANOSECONDS;
453 case MICROS: return TimeUnit.MICROSECONDS;
454 case MILLIS: return TimeUnit.MILLISECONDS;
455 case SECONDS: return TimeUnit.SECONDS;
456 case MINUTES: return TimeUnit.MINUTES;
457 case HOURS: return TimeUnit.HOURS;
458 case DAYS: return TimeUnit.DAYS;
459 default:
460 throw new IllegalArgumentException(
461 "No TimeUnit equivalent for " + chronoUnit);
462 }
463 }
464
465 }