ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/TimeUnit.java
Revision: 1.48
Committed: Fri Jan 29 20:02:39 2016 UTC (8 years, 4 months ago) by jsr166
Branch: MAIN
Changes since 1.47: +47 -0 lines
Log Message:
Implement 8141452: Convert between TimeUnit and ChronoUnit

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.temporal.ChronoUnit;
10 import java.util.Objects;
11
12 /**
13 * A {@code TimeUnit} represents time durations at a given unit of
14 * granularity and provides utility methods to convert across units,
15 * and to perform timing and delay operations in these units. A
16 * {@code TimeUnit} does not maintain time information, but only
17 * 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 * <p>A {@code TimeUnit} is mainly used to inform time-based methods
25 * 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 * <pre> {@code
30 * Lock lock = ...;
31 * if (lock.tryLock(50L, TimeUnit.MILLISECONDS)) ...}</pre>
32 *
33 * while this code will timeout in 50 seconds:
34 * <pre> {@code
35 * Lock lock = ...;
36 * if (lock.tryLock(50L, TimeUnit.SECONDS)) ...}</pre>
37 *
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 * same granularity as the given {@code TimeUnit}.
41 *
42 * @since 1.5
43 * @author Doug Lea
44 */
45 public enum TimeUnit {
46 /**
47 * Time unit representing one thousandth of a microsecond.
48 */
49 NANOSECONDS {
50 public long toNanos(long d) { return d; }
51 public long toMicros(long d) { return d/(C1/C0); }
52 public long toMillis(long d) { return d/(C2/C0); }
53 public long toSeconds(long d) { return d/(C3/C0); }
54 public long toMinutes(long d) { return d/(C4/C0); }
55 public long toHours(long d) { return d/(C5/C0); }
56 public long toDays(long d) { return d/(C6/C0); }
57 public long convert(long d, TimeUnit u) { return u.toNanos(d); }
58 int excessNanos(long d, long m) { return (int)(d - (m*C2)); }
59 },
60
61 /**
62 * Time unit representing one thousandth of a millisecond.
63 */
64 MICROSECONDS {
65 public long toNanos(long d) { return x(d, C1/C0, MAX/(C1/C0)); }
66 public long toMicros(long d) { return d; }
67 public long toMillis(long d) { return d/(C2/C1); }
68 public long toSeconds(long d) { return d/(C3/C1); }
69 public long toMinutes(long d) { return d/(C4/C1); }
70 public long toHours(long d) { return d/(C5/C1); }
71 public long toDays(long d) { return d/(C6/C1); }
72 public long convert(long d, TimeUnit u) { return u.toMicros(d); }
73 int excessNanos(long d, long m) { return (int)((d*C1) - (m*C2)); }
74 },
75
76 /**
77 * Time unit representing one thousandth of a second.
78 */
79 MILLISECONDS {
80 public long toNanos(long d) { return x(d, C2/C0, MAX/(C2/C0)); }
81 public long toMicros(long d) { return x(d, C2/C1, MAX/(C2/C1)); }
82 public long toMillis(long d) { return d; }
83 public long toSeconds(long d) { return d/(C3/C2); }
84 public long toMinutes(long d) { return d/(C4/C2); }
85 public long toHours(long d) { return d/(C5/C2); }
86 public long toDays(long d) { return d/(C6/C2); }
87 public long convert(long d, TimeUnit u) { return u.toMillis(d); }
88 int excessNanos(long d, long m) { return 0; }
89 },
90
91 /**
92 * Time unit representing one second.
93 */
94 SECONDS {
95 public long toNanos(long d) { return x(d, C3/C0, MAX/(C3/C0)); }
96 public long toMicros(long d) { return x(d, C3/C1, MAX/(C3/C1)); }
97 public long toMillis(long d) { return x(d, C3/C2, MAX/(C3/C2)); }
98 public long toSeconds(long d) { return d; }
99 public long toMinutes(long d) { return d/(C4/C3); }
100 public long toHours(long d) { return d/(C5/C3); }
101 public long toDays(long d) { return d/(C6/C3); }
102 public long convert(long d, TimeUnit u) { return u.toSeconds(d); }
103 int excessNanos(long d, long m) { return 0; }
104 },
105
106 /**
107 * Time unit representing sixty seconds.
108 * @since 1.6
109 */
110 MINUTES {
111 public long toNanos(long d) { return x(d, C4/C0, MAX/(C4/C0)); }
112 public long toMicros(long d) { return x(d, C4/C1, MAX/(C4/C1)); }
113 public long toMillis(long d) { return x(d, C4/C2, MAX/(C4/C2)); }
114 public long toSeconds(long d) { return x(d, C4/C3, MAX/(C4/C3)); }
115 public long toMinutes(long d) { return d; }
116 public long toHours(long d) { return d/(C5/C4); }
117 public long toDays(long d) { return d/(C6/C4); }
118 public long convert(long d, TimeUnit u) { return u.toMinutes(d); }
119 int excessNanos(long d, long m) { return 0; }
120 },
121
122 /**
123 * Time unit representing sixty minutes.
124 * @since 1.6
125 */
126 HOURS {
127 public long toNanos(long d) { return x(d, C5/C0, MAX/(C5/C0)); }
128 public long toMicros(long d) { return x(d, C5/C1, MAX/(C5/C1)); }
129 public long toMillis(long d) { return x(d, C5/C2, MAX/(C5/C2)); }
130 public long toSeconds(long d) { return x(d, C5/C3, MAX/(C5/C3)); }
131 public long toMinutes(long d) { return x(d, C5/C4, MAX/(C5/C4)); }
132 public long toHours(long d) { return d; }
133 public long toDays(long d) { return d/(C6/C5); }
134 public long convert(long d, TimeUnit u) { return u.toHours(d); }
135 int excessNanos(long d, long m) { return 0; }
136 },
137
138 /**
139 * Time unit representing twenty four hours.
140 * @since 1.6
141 */
142 DAYS {
143 public long toNanos(long d) { return x(d, C6/C0, MAX/(C6/C0)); }
144 public long toMicros(long d) { return x(d, C6/C1, MAX/(C6/C1)); }
145 public long toMillis(long d) { return x(d, C6/C2, MAX/(C6/C2)); }
146 public long toSeconds(long d) { return x(d, C6/C3, MAX/(C6/C3)); }
147 public long toMinutes(long d) { return x(d, C6/C4, MAX/(C6/C4)); }
148 public long toHours(long d) { return x(d, C6/C5, MAX/(C6/C5)); }
149 public long toDays(long d) { return d; }
150 public long convert(long d, TimeUnit u) { return u.toDays(d); }
151 int excessNanos(long d, long m) { return 0; }
152 };
153
154 // Handy constants for conversion methods
155 static final long C0 = 1L;
156 static final long C1 = C0 * 1000L;
157 static final long C2 = C1 * 1000L;
158 static final long C3 = C2 * 1000L;
159 static final long C4 = C3 * 60L;
160 static final long C5 = C4 * 60L;
161 static final long C6 = C5 * 24L;
162
163 static final long MAX = Long.MAX_VALUE;
164
165 /**
166 * Scale d by m, checking for overflow.
167 * This has a short name to make above code more readable.
168 */
169 static long x(long d, long m, long over) {
170 if (d > +over) return Long.MAX_VALUE;
171 if (d < -over) return Long.MIN_VALUE;
172 return d * m;
173 }
174
175 // To maintain full signature compatibility with 1.5, and to improve the
176 // clarity of the generated javadoc (see 6287639: Abstract methods in
177 // enum classes should not be listed as abstract), method convert
178 // etc. are not declared abstract but otherwise act as abstract methods.
179
180 /**
181 * Converts the given time duration in the given unit to this unit.
182 * Conversions from finer to coarser granularities truncate, so
183 * lose precision. For example, converting {@code 999} milliseconds
184 * to seconds results in {@code 0}. Conversions from coarser to
185 * finer granularities with arguments that would numerically
186 * overflow saturate to {@code Long.MIN_VALUE} if negative or
187 * {@code Long.MAX_VALUE} if positive.
188 *
189 * <p>For example, to convert 10 minutes to milliseconds, use:
190 * {@code TimeUnit.MILLISECONDS.convert(10L, TimeUnit.MINUTES)}
191 *
192 * @param sourceDuration the time duration in the given {@code sourceUnit}
193 * @param sourceUnit the unit of the {@code sourceDuration} argument
194 * @return the converted duration in this unit,
195 * or {@code Long.MIN_VALUE} if conversion would negatively
196 * overflow, or {@code Long.MAX_VALUE} if it would positively overflow.
197 */
198 public long convert(long sourceDuration, TimeUnit sourceUnit) {
199 throw new AbstractMethodError();
200 }
201
202 /**
203 * Equivalent to
204 * {@link #convert(long, TimeUnit) NANOSECONDS.convert(duration, this)}.
205 * @param duration the duration
206 * @return the converted duration,
207 * or {@code Long.MIN_VALUE} if conversion would negatively
208 * overflow, or {@code Long.MAX_VALUE} if it would positively overflow.
209 */
210 public long toNanos(long duration) {
211 throw new AbstractMethodError();
212 }
213
214 /**
215 * Equivalent to
216 * {@link #convert(long, TimeUnit) MICROSECONDS.convert(duration, this)}.
217 * @param duration the duration
218 * @return the converted duration,
219 * or {@code Long.MIN_VALUE} if conversion would negatively
220 * overflow, or {@code Long.MAX_VALUE} if it would positively overflow.
221 */
222 public long toMicros(long duration) {
223 throw new AbstractMethodError();
224 }
225
226 /**
227 * Equivalent to
228 * {@link #convert(long, TimeUnit) MILLISECONDS.convert(duration, this)}.
229 * @param duration the duration
230 * @return the converted duration,
231 * or {@code Long.MIN_VALUE} if conversion would negatively
232 * overflow, or {@code Long.MAX_VALUE} if it would positively overflow.
233 */
234 public long toMillis(long duration) {
235 throw new AbstractMethodError();
236 }
237
238 /**
239 * Equivalent to
240 * {@link #convert(long, TimeUnit) SECONDS.convert(duration, this)}.
241 * @param duration the duration
242 * @return the converted duration,
243 * or {@code Long.MIN_VALUE} if conversion would negatively
244 * overflow, or {@code Long.MAX_VALUE} if it would positively overflow.
245 */
246 public long toSeconds(long duration) {
247 throw new AbstractMethodError();
248 }
249
250 /**
251 * Equivalent to
252 * {@link #convert(long, TimeUnit) MINUTES.convert(duration, this)}.
253 * @param duration the duration
254 * @return the converted duration,
255 * or {@code Long.MIN_VALUE} if conversion would negatively
256 * overflow, or {@code Long.MAX_VALUE} if it would positively overflow.
257 * @since 1.6
258 */
259 public long toMinutes(long duration) {
260 throw new AbstractMethodError();
261 }
262
263 /**
264 * Equivalent to
265 * {@link #convert(long, TimeUnit) HOURS.convert(duration, this)}.
266 * @param duration the duration
267 * @return the converted duration,
268 * or {@code Long.MIN_VALUE} if conversion would negatively
269 * overflow, or {@code Long.MAX_VALUE} if it would positively overflow.
270 * @since 1.6
271 */
272 public long toHours(long duration) {
273 throw new AbstractMethodError();
274 }
275
276 /**
277 * Equivalent to
278 * {@link #convert(long, TimeUnit) DAYS.convert(duration, this)}.
279 * @param duration the duration
280 * @return the converted duration
281 * @since 1.6
282 */
283 public long toDays(long duration) {
284 throw new AbstractMethodError();
285 }
286
287 /**
288 * Utility to compute the excess-nanosecond argument to wait,
289 * sleep, join.
290 * @param d the duration
291 * @param m the number of milliseconds
292 * @return the number of nanoseconds
293 */
294 abstract int excessNanos(long d, long m);
295
296 /**
297 * Performs a timed {@link Object#wait(long, int) Object.wait}
298 * using this time unit.
299 * This is a convenience method that converts timeout arguments
300 * into the form required by the {@code Object.wait} method.
301 *
302 * <p>For example, you could implement a blocking {@code poll}
303 * method (see {@link BlockingQueue#poll BlockingQueue.poll})
304 * using:
305 *
306 * <pre> {@code
307 * public synchronized Object poll(long timeout, TimeUnit unit)
308 * throws InterruptedException {
309 * while (empty) {
310 * unit.timedWait(this, timeout);
311 * ...
312 * }
313 * }}</pre>
314 *
315 * @param obj the object to wait on
316 * @param timeout the maximum time to wait. If less than
317 * or equal to zero, do not wait at all.
318 * @throws InterruptedException if interrupted while waiting
319 */
320 public void timedWait(Object obj, long timeout)
321 throws InterruptedException {
322 if (timeout > 0) {
323 long ms = toMillis(timeout);
324 int ns = excessNanos(timeout, ms);
325 obj.wait(ms, ns);
326 }
327 }
328
329 /**
330 * Performs a timed {@link Thread#join(long, int) Thread.join}
331 * using this time unit.
332 * This is a convenience method that converts time arguments into the
333 * form required by the {@code Thread.join} method.
334 *
335 * @param thread the thread to wait for
336 * @param timeout the maximum time to wait. If less than
337 * or equal to zero, do not wait at all.
338 * @throws InterruptedException if interrupted while waiting
339 */
340 public void timedJoin(Thread thread, long timeout)
341 throws InterruptedException {
342 if (timeout > 0) {
343 long ms = toMillis(timeout);
344 int ns = excessNanos(timeout, ms);
345 thread.join(ms, ns);
346 }
347 }
348
349 /**
350 * Performs a {@link Thread#sleep(long, int) Thread.sleep} using
351 * this time unit.
352 * This is a convenience method that converts time arguments into the
353 * form required by the {@code Thread.sleep} method.
354 *
355 * @param timeout the minimum time to sleep. If less than
356 * or equal to zero, do not sleep at all.
357 * @throws InterruptedException if interrupted while sleeping
358 */
359 public void sleep(long timeout) throws InterruptedException {
360 if (timeout > 0) {
361 long ms = toMillis(timeout);
362 int ns = excessNanos(timeout, ms);
363 Thread.sleep(ms, ns);
364 }
365 }
366
367 /**
368 * Converts this {@code TimeUnit} to the equivalent {@code ChronoUnit}.
369 *
370 * @return the converted equivalent ChronoUnit
371 * @since 9
372 */
373 public ChronoUnit toChronoUnit() {
374 switch (this) {
375 case NANOSECONDS: return ChronoUnit.NANOS;
376 case MICROSECONDS: return ChronoUnit.MICROS;
377 case MILLISECONDS: return ChronoUnit.MILLIS;
378 case SECONDS: return ChronoUnit.SECONDS;
379 case MINUTES: return ChronoUnit.MINUTES;
380 case HOURS: return ChronoUnit.HOURS;
381 case DAYS: return ChronoUnit.DAYS;
382 default: throw new AssertionError();
383 }
384 }
385
386 /**
387 * Converts a {@code ChronoUnit} to the equivalent {@code TimeUnit}.
388 *
389 * @param chronoUnit the ChronoUnit to convert
390 * @return the converted equivalent TimeUnit
391 * @throws IllegalArgumentException if {@code chronoUnit} has no
392 * equivalent TimeUnit
393 * @throws NullPointerException if {@code chronoUnit} is null
394 * @since 9
395 */
396 public static TimeUnit of(ChronoUnit chronoUnit) {
397 switch (Objects.requireNonNull(chronoUnit, "chronoUnit")) {
398 case NANOS: return TimeUnit.NANOSECONDS;
399 case MICROS: return TimeUnit.MICROSECONDS;
400 case MILLIS: return TimeUnit.MILLISECONDS;
401 case SECONDS: return TimeUnit.SECONDS;
402 case MINUTES: return TimeUnit.MINUTES;
403 case HOURS: return TimeUnit.HOURS;
404 case DAYS: return TimeUnit.DAYS;
405 default:
406 throw new IllegalArgumentException(
407 "No TimeUnit equivalent for " + chronoUnit);
408 }
409 }
410
411 }