ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/TimeUnit.java
(Generate patch)

Comparing jsr166/src/main/java/util/concurrent/TimeUnit.java (file contents):
Revision 1.27 by dl, Tue Mar 8 12:27:11 2005 UTC vs.
Revision 1.66 by jsr166, Sun Jun 10 01:18:10 2018 UTC

# Line 1 | Line 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/licenses/publicdomain
5 <  */
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 <tt>TimeUnit</tt> represents time durations at a given unit of
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 < * <tt>TimeUnit</tt> does not maintain time information, but only
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
# Line 18 | Line 22 | package java.util.concurrent;
22   * as sixty seconds, an hour as sixty minutes, and a day as twenty four
23   * hours.
24   *
25 < * <p>A <tt>TimeUnit</tt> is mainly used to inform time-based methods
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>  Lock lock = ...;
31 < *  if ( lock.tryLock(50L, TimeUnit.MILLISECONDS) ) ...
32 < * </pre>
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>
36 < *  Lock lock = ...;
37 < *  if ( lock.tryLock(50L, TimeUnit.SECONDS) ) ...
33 < * </pre>
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 <tt>TimeUnit</tt>.
41 > * same granularity as the given {@code TimeUnit}.
42   *
43   * @since 1.5
44   * @author Doug Lea
45   */
46   public enum TimeUnit {
47 <    NANOSECONDS (0) {
48 <        public long toNanos(long d)   { return d; }
49 <        public long toMicros(long d)  { return d/(C1/C0); }
50 <        public long toMillis(long d)  { return d/(C2/C0); }
51 <        public long toSeconds(long d) { return d/(C3/C0); }
52 <        public long toMinutes(long d) { return d/(C4/C0); }
53 <        public long toHours(long d)   { return d/(C5/C0); }
54 <        public long toDays(long d)    { return d/(C6/C0); }
55 <        public long convert(long d, TimeUnit u) { return u.toNanos(d); }
56 <        int excessNanos(long d, long m) { return (int)(d - (m*C2)); }
57 <    },
58 <    MICROSECONDS (1) {
59 <        public long toNanos(long d)   { return x(d, C1/C0, MAX/(C1/C0)); }
60 <        public long toMicros(long d)  { return d; }
61 <        public long toMillis(long d)  { return d/(C2/C1); }
62 <        public long toSeconds(long d) { return d/(C3/C1); }
63 <        public long toMinutes(long d) { return d/(C4/C1); }
64 <        public long toHours(long d)   { return d/(C5/C1); }
65 <        public long toDays(long d)    { return d/(C6/C1); }
66 <        public long convert(long d, TimeUnit u) { return u.toMicros(d); }
67 <        int excessNanos(long d, long m) { return (int)((d*C1) - (m*C2)); }
68 <    },
69 <    MILLISECONDS (2) {
70 <        public long toNanos(long d)   { return x(d, C2/C0, MAX/(C2/C0)); }
71 <        public long toMicros(long d)  { return x(d, C2/C1, MAX/(C2/C1)); }
72 <        public long toMillis(long d)  { return d; }
73 <        public long toSeconds(long d) { return d/(C3/C2); }
74 <        public long toMinutes(long d) { return d/(C4/C2); }
75 <        public long toHours(long d)   { return d/(C5/C2); }
76 <        public long toDays(long d)    { return d/(C6/C2); }
77 <        public long convert(long d, TimeUnit u) { return u.toMillis(d); }
78 <        int excessNanos(long d, long m) { return 0; }
79 <    },
80 <    SECONDS (3) {
81 <        public long toNanos(long d)   { return x(d, C3/C0, MAX/(C3/C0)); }
82 <        public long toMicros(long d)  { return x(d, C3/C1, MAX/(C3/C1)); }
83 <        public long toMillis(long d)  { return x(d, C3/C2, MAX/(C3/C2)); }
84 <        public long toSeconds(long d) { return d; }
85 <        public long toMinutes(long d) { return d/(C4/C3); }
86 <        public long toHours(long d)   { return d/(C5/C3); }
87 <        public long toDays(long d)    { return d/(C6/C3); }
88 <        public long convert(long d, TimeUnit u) { return u.toSeconds(d); }
89 <        int excessNanos(long d, long m) { return 0; }
90 <    },
91 <    MINUTES (4) {
92 <        public long toNanos(long d)   { return x(d, C4/C0, MAX/(C4/C0)); }
93 <        public long toMicros(long d)  { return x(d, C4/C1, MAX/(C4/C1)); }
94 <        public long toMillis(long d)  { return x(d, C4/C2, MAX/(C4/C2)); }
95 <        public long toSeconds(long d) { return x(d, C4/C3, MAX/(C4/C3)); }
96 <        public long toMinutes(long d) { return d; }
97 <        public long toHours(long d)   { return d/(C5/C4); }
98 <        public long toDays(long d)    { return d/(C6/C4); }
99 <        public long convert(long d, TimeUnit u) { return u.toMinutes(d); }
100 <        int excessNanos(long d, long m) { return 0; }
101 <    },
102 <    HOURS (5) {
103 <        public long toNanos(long d)   { return x(d, C5/C0, MAX/(C5/C0)); }
104 <        public long toMicros(long d)  { return x(d, C5/C1, MAX/(C5/C1)); }
105 <        public long toMillis(long d)  { return x(d, C5/C2, MAX/(C5/C2)); }
106 <        public long toSeconds(long d) { return x(d, C5/C3, MAX/(C5/C3)); }
107 <        public long toMinutes(long d) { return x(d, C5/C4, MAX/(C5/C4)); }
108 <        public long toHours(long d)   { return d; }
109 <        public long toDays(long d)    { return d/(C6/C5); }
110 <        public long convert(long d, TimeUnit u) { return u.toHours(d); }
111 <        int excessNanos(long d, long m) { return 0; }
112 <    },
113 <    DAYS (6) {
114 <        public long toNanos(long d)   { return x(d, C6/C0, MAX/(C6/C0)); }
115 <        public long toMicros(long d)  { return x(d, C6/C1, MAX/(C6/C1)); }
116 <        public long toMillis(long d)  { return x(d, C6/C2, MAX/(C6/C2)); }
117 <        public long toSeconds(long d) { return x(d, C6/C3, MAX/(C6/C3)); }
118 <        public long toMinutes(long d) { return x(d, C6/C4, MAX/(C6/C4)); }
119 <        public long toHours(long d)   { return x(d, C6/C5, MAX/(C6/C5)); }
120 <        public long toDays(long d)    { return d; }
121 <        public long convert(long d, TimeUnit u) { return u.toDays(d); }
122 <        int excessNanos(long d, long m) { return 0; }
123 <    };
124 <    
125 <    /**
126 <     * The index of this unit. This value is no longer used in this
127 <     * version of this class, but is retained for serialization
128 <     * compatibility with previous version.
129 <     */
130 <    private final int index;
131 <    
132 <    /** Internal constructor */
133 <    TimeUnit(int index) {
134 <        this.index = index;
135 <    }
136 <    
137 <    // Handy constants for conversion methods
138 <    static final long C0 = 1L;
139 <    static final long C1 = C0 * 1000L;
140 <    static final long C2 = C1 * 1000L;
141 <    static final long C3 = C2 * 1000L;
142 <    static final long C4 = C3 * 60L;
143 <    static final long C5 = C4 * 60L;
144 <    static final long C6 = C5 * 24L;
145 <    
146 <    static final long MAX = Long.MAX_VALUE;
147 <    
148 <    /**
145 <     * Scale d by m, checking for overflow.
146 <     * This has a short name to make above code more readable.
147 <     */
148 <    static long x(long d, long m, long over) {
149 <        if (d >  over) return Long.MAX_VALUE;
150 <        if (d < -over) return Long.MIN_VALUE;
151 <        return d * m;
152 <    }
153 <    
154 <    /**
155 <     * Convert the given time duration in the given unit to this
156 <     * unit.  Conversions from finer to coarser granularities
157 <     * truncate, so lose precision. For example converting
158 <     * <tt>999</tt> milliseconds to seconds results in
159 <     * <tt>0</tt>. Conversions from coarser to finer granularities
160 <     * with arguments that would numerically overflow saturate to
161 <     * <tt>Long.MIN_VALUE</tt> if negative or <tt>Long.MAX_VALUE</tt>
162 <     * if positive.
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 duration the time duration in the given <tt>unit</tt>
151 <     * @param unit the unit of the <tt>duration</tt> argument
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 <tt>Long.MIN_VALUE</tt> if conversion would negatively
154 <     * overflow, or <tt>Long.MAX_VALUE</tt> if it would positively overflow.
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 abstract long convert(long duration, TimeUnit unit);
157 <    
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 <     * Equivalent to <tt>NANOSECONDS.convert(duration, this)</tt>.
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 >     * <p>This method differs from {@link Duration#toNanos()} in that
177 >     * it does not throw {@link ArithmeticException} on numeric overflow.
178 >     *
179 >     * @param duration the time duration
180 >     * @return the converted duration in this unit,
181 >     * or {@code Long.MIN_VALUE} if conversion would negatively overflow,
182 >     * or {@code Long.MAX_VALUE} if it would positively overflow.
183 >     * @throws NullPointerException if {@code duration} is null
184 >     * @see Duration#of(long,TemporalUnit)
185 >     * @since 11
186 >     */
187 >    public long convert(Duration duration) {
188 >        long secs = duration.getSeconds();
189 >        int nano = duration.getNano();
190 >        if (secs < 0 && nano > 0) {
191 >            // use representation compatible with integer division
192 >            secs++;
193 >            nano -= (int) SECOND_SCALE;
194 >        }
195 >        final long s, nanoVal;
196 >        // Optimize for the common case - NANOSECONDS without overflow
197 >        if (this == NANOSECONDS)
198 >            nanoVal = nano;
199 >        else if ((s = scale) < SECOND_SCALE)
200 >            nanoVal = nano / s;
201 >        else if (this == SECONDS)
202 >            return secs;
203 >        else
204 >            return secs / secRatio;
205 >        long val = secs * secRatio + nanoVal;
206 >        return ((secs < maxSecs && secs > -maxSecs) ||
207 >                (secs == maxSecs && val > 0) ||
208 >                (secs == -maxSecs && val < 0))
209 >            ? val
210 >            : (secs > 0) ? Long.MAX_VALUE : Long.MIN_VALUE;
211 >    }
212 >
213 >    /**
214 >     * Equivalent to
215 >     * {@link #convert(long, TimeUnit) NANOSECONDS.convert(duration, this)}.
216       * @param duration the duration
217       * @return the converted duration,
218 <     * or <tt>Long.MIN_VALUE</tt> if conversion would negatively
219 <     * overflow, or <tt>Long.MAX_VALUE</tt> if it would positively overflow.
178 <     * @see #convert
218 >     * or {@code Long.MIN_VALUE} if conversion would negatively overflow,
219 >     * or {@code Long.MAX_VALUE} if it would positively overflow.
220       */
221 <    public abstract long toNanos(long duration);
222 <    
221 >    public long toNanos(long duration) {
222 >        long s, m;
223 >        if ((s = scale) == NANO_SCALE)
224 >            return duration;
225 >        else if (duration > (m = maxNanos))
226 >            return Long.MAX_VALUE;
227 >        else if (duration < -m)
228 >            return Long.MIN_VALUE;
229 >        else
230 >            return duration * s;
231 >    }
232 >
233      /**
234 <     * Equivalent to <tt>MICROSECONDS.convert(duration, this)</tt>.
234 >     * Equivalent to
235 >     * {@link #convert(long, TimeUnit) MICROSECONDS.convert(duration, this)}.
236       * @param duration the duration
237       * @return the converted duration,
238 <     * or <tt>Long.MIN_VALUE</tt> if conversion would negatively
239 <     * overflow, or <tt>Long.MAX_VALUE</tt> if it would positively overflow.
188 <     * @see #convert
238 >     * or {@code Long.MIN_VALUE} if conversion would negatively overflow,
239 >     * or {@code Long.MAX_VALUE} if it would positively overflow.
240       */
241 <    public abstract long toMicros(long duration);
242 <    
241 >    public long toMicros(long duration) {
242 >        long s, m;
243 >        if ((s = scale) <= MICRO_SCALE)
244 >            return (s == MICRO_SCALE) ? duration : duration / microRatio;
245 >        else if (duration > (m = maxMicros))
246 >            return Long.MAX_VALUE;
247 >        else if (duration < -m)
248 >            return Long.MIN_VALUE;
249 >        else
250 >            return duration * microRatio;
251 >    }
252 >
253      /**
254 <     * Equivalent to <tt>MILLISECONDS.convert(duration, this)</tt>.
254 >     * Equivalent to
255 >     * {@link #convert(long, TimeUnit) MILLISECONDS.convert(duration, this)}.
256       * @param duration the duration
257       * @return the converted duration,
258 <     * or <tt>Long.MIN_VALUE</tt> if conversion would negatively
259 <     * overflow, or <tt>Long.MAX_VALUE</tt> if it would positively overflow.
198 <     * @see #convert
258 >     * or {@code Long.MIN_VALUE} if conversion would negatively overflow,
259 >     * or {@code Long.MAX_VALUE} if it would positively overflow.
260       */
261 <    public abstract long toMillis(long duration);
262 <    
261 >    public long toMillis(long duration) {
262 >        long s, m;
263 >        if ((s = scale) <= MILLI_SCALE)
264 >            return (s == MILLI_SCALE) ? duration : duration / milliRatio;
265 >        else if (duration > (m = maxMillis))
266 >            return Long.MAX_VALUE;
267 >        else if (duration < -m)
268 >            return Long.MIN_VALUE;
269 >        else
270 >            return duration * milliRatio;
271 >    }
272 >
273      /**
274 <     * Equivalent to <tt>SECONDS.convert(duration, this)</tt>.
274 >     * Equivalent to
275 >     * {@link #convert(long, TimeUnit) SECONDS.convert(duration, this)}.
276       * @param duration the duration
277       * @return the converted duration,
278 <     * or <tt>Long.MIN_VALUE</tt> if conversion would negatively
279 <     * overflow, or <tt>Long.MAX_VALUE</tt> if it would positively overflow.
208 <     * @see #convert
278 >     * or {@code Long.MIN_VALUE} if conversion would negatively overflow,
279 >     * or {@code Long.MAX_VALUE} if it would positively overflow.
280       */
281 <    public abstract long toSeconds(long duration);
282 <    
281 >    public long toSeconds(long duration) {
282 >        long s, m;
283 >        if ((s = scale) <= SECOND_SCALE)
284 >            return (s == SECOND_SCALE) ? duration : duration / secRatio;
285 >        else if (duration > (m = maxSecs))
286 >            return Long.MAX_VALUE;
287 >        else if (duration < -m)
288 >            return Long.MIN_VALUE;
289 >        else
290 >            return duration * secRatio;
291 >    }
292 >
293      /**
294 <     * Equivalent to <tt>MINUTES.convert(duration, this)</tt>.
294 >     * Equivalent to
295 >     * {@link #convert(long, TimeUnit) MINUTES.convert(duration, this)}.
296       * @param duration the duration
297       * @return the converted duration,
298 <     * or <tt>Long.MIN_VALUE</tt> if conversion would negatively
299 <     * overflow, or <tt>Long.MAX_VALUE</tt> if it would positively overflow.
300 <     * @see #convert
298 >     * or {@code Long.MIN_VALUE} if conversion would negatively overflow,
299 >     * or {@code Long.MAX_VALUE} if it would positively overflow.
300 >     * @since 1.6
301       */
302 <    public abstract long toMinutes(long duration);
303 <    
302 >    public long toMinutes(long duration) {
303 >        return cvt(duration, MINUTE_SCALE, scale);
304 >    }
305 >
306      /**
307 <     * Equivalent to <tt>HOURS.convert(duration, this)</tt>.
307 >     * Equivalent to
308 >     * {@link #convert(long, TimeUnit) HOURS.convert(duration, this)}.
309       * @param duration the duration
310       * @return the converted duration,
311 <     * or <tt>Long.MIN_VALUE</tt> if conversion would negatively
312 <     * overflow, or <tt>Long.MAX_VALUE</tt> if it would positively overflow.
313 <     * @see #convert
311 >     * or {@code Long.MIN_VALUE} if conversion would negatively overflow,
312 >     * or {@code Long.MAX_VALUE} if it would positively overflow.
313 >     * @since 1.6
314       */
315 <    public abstract long toHours(long duration);
316 <    
315 >    public long toHours(long duration) {
316 >        return cvt(duration, HOUR_SCALE, scale);
317 >    }
318 >
319      /**
320 <     * Equivalent to <tt>DAYS.convert(duration, this)</tt>.
320 >     * Equivalent to
321 >     * {@link #convert(long, TimeUnit) DAYS.convert(duration, this)}.
322       * @param duration the duration
323       * @return the converted duration
324 <     * @see #convert
324 >     * @since 1.6
325       */
326 <    public abstract long toDays(long duration);
327 <    
326 >    public long toDays(long duration) {
327 >        return cvt(duration, DAY_SCALE, scale);
328 >    }
329 >
330      /**
331       * Utility to compute the excess-nanosecond argument to wait,
332       * sleep, join.
# Line 244 | Line 334 | public enum TimeUnit {
334       * @param m the number of milliseconds
335       * @return the number of nanoseconds
336       */
337 <    abstract int excessNanos(long d, long m);
338 <    
337 >    private int excessNanos(long d, long m) {
338 >        long s;
339 >        if ((s = scale) == NANO_SCALE)
340 >            return (int)(d - (m * MILLI_SCALE));
341 >        else if (s == MICRO_SCALE)
342 >            return (int)((d * 1000L) - (m * MILLI_SCALE));
343 >        else
344 >            return 0;
345 >    }
346 >
347      /**
348 <     * Perform a timed <tt>Object.wait</tt> using this time unit.
348 >     * Performs a timed {@link Object#wait(long, int) Object.wait}
349 >     * using this time unit.
350       * This is a convenience method that converts timeout arguments
351 <     * into the form required by the <tt>Object.wait</tt> method.
351 >     * into the form required by the {@code Object.wait} method.
352       *
353 <     * <p>For example, you could implement a blocking <tt>poll</tt>
354 <     * method (see {@link BlockingQueue#poll BlockingQueue.poll})
353 >     * <p>For example, you could implement a blocking {@code poll} method
354 >     * (see {@link BlockingQueue#poll(long, TimeUnit) BlockingQueue.poll})
355       * using:
356       *
357 <     * <pre>  public synchronized  Object poll(long timeout, TimeUnit unit) throws InterruptedException {
358 <     *    while (empty) {
359 <     *      unit.timedWait(this, timeout);
360 <     *      ...
361 <     *    }
362 <     *  }</pre>
357 >     * <pre> {@code
358 >     * public E poll(long timeout, TimeUnit unit)
359 >     *     throws InterruptedException {
360 >     *   synchronized (lock) {
361 >     *     while (isEmpty()) {
362 >     *       unit.timedWait(lock, timeout);
363 >     *       ...
364 >     *     }
365 >     *   }
366 >     * }}</pre>
367       *
368       * @param obj the object to wait on
369 <     * @param timeout the maximum time to wait.
370 <     * @throws InterruptedException if interrupted while waiting.
371 <     * @see Object#wait(long, int)
369 >     * @param timeout the maximum time to wait. If less than
370 >     * or equal to zero, do not wait at all.
371 >     * @throws InterruptedException if interrupted while waiting
372       */
373      public void timedWait(Object obj, long timeout)
374 <    throws InterruptedException {
374 >            throws InterruptedException {
375          if (timeout > 0) {
376              long ms = toMillis(timeout);
377              int ns = excessNanos(timeout, ms);
378              obj.wait(ms, ns);
379          }
380      }
381 <    
381 >
382      /**
383 <     * Perform a timed <tt>Thread.join</tt> using this time unit.
383 >     * Performs a timed {@link Thread#join(long, int) Thread.join}
384 >     * using this time unit.
385       * This is a convenience method that converts time arguments into the
386 <     * form required by the <tt>Thread.join</tt> method.
386 >     * form required by the {@code Thread.join} method.
387 >     *
388       * @param thread the thread to wait for
389 <     * @param timeout the maximum time to wait
390 <     * @throws InterruptedException if interrupted while waiting.
391 <     * @see Thread#join(long, int)
389 >     * @param timeout the maximum time to wait. If less than
390 >     * or equal to zero, do not wait at all.
391 >     * @throws InterruptedException if interrupted while waiting
392       */
393      public void timedJoin(Thread thread, long timeout)
394 <    throws InterruptedException {
394 >            throws InterruptedException {
395          if (timeout > 0) {
396              long ms = toMillis(timeout);
397              int ns = excessNanos(timeout, ms);
398              thread.join(ms, ns);
399          }
400      }
401 <    
401 >
402      /**
403 <     * Perform a <tt>Thread.sleep</tt> using this unit.
403 >     * Performs a {@link Thread#sleep(long, int) Thread.sleep} using
404 >     * this time unit.
405       * This is a convenience method that converts time arguments into the
406 <     * form required by the <tt>Thread.sleep</tt> method.
407 <     * @param timeout the minimum time to sleep
408 <     * @throws InterruptedException if interrupted while sleeping.
409 <     * @see Thread#sleep
406 >     * form required by the {@code Thread.sleep} method.
407 >     *
408 >     * @param timeout the minimum time to sleep. If less than
409 >     * or equal to zero, do not sleep at all.
410 >     * @throws InterruptedException if interrupted while sleeping
411       */
412      public void sleep(long timeout) throws InterruptedException {
413          if (timeout > 0) {
# Line 309 | Line 416 | public enum TimeUnit {
416              Thread.sleep(ms, ns);
417          }
418      }
419 <    
419 >
420 >    /**
421 >     * Converts this {@code TimeUnit} to the equivalent {@code ChronoUnit}.
422 >     *
423 >     * @return the converted equivalent ChronoUnit
424 >     * @since 9
425 >     */
426 >    public ChronoUnit toChronoUnit() {
427 >        switch (this) {
428 >        case NANOSECONDS:  return ChronoUnit.NANOS;
429 >        case MICROSECONDS: return ChronoUnit.MICROS;
430 >        case MILLISECONDS: return ChronoUnit.MILLIS;
431 >        case SECONDS:      return ChronoUnit.SECONDS;
432 >        case MINUTES:      return ChronoUnit.MINUTES;
433 >        case HOURS:        return ChronoUnit.HOURS;
434 >        case DAYS:         return ChronoUnit.DAYS;
435 >        default: throw new AssertionError();
436 >        }
437 >    }
438 >
439 >    /**
440 >     * Converts a {@code ChronoUnit} to the equivalent {@code TimeUnit}.
441 >     *
442 >     * @param chronoUnit the ChronoUnit to convert
443 >     * @return the converted equivalent TimeUnit
444 >     * @throws IllegalArgumentException if {@code chronoUnit} has no
445 >     *         equivalent TimeUnit
446 >     * @throws NullPointerException if {@code chronoUnit} is null
447 >     * @since 9
448 >     */
449 >    public static TimeUnit of(ChronoUnit chronoUnit) {
450 >        switch (Objects.requireNonNull(chronoUnit, "chronoUnit")) {
451 >        case NANOS:   return TimeUnit.NANOSECONDS;
452 >        case MICROS:  return TimeUnit.MICROSECONDS;
453 >        case MILLIS:  return TimeUnit.MILLISECONDS;
454 >        case SECONDS: return TimeUnit.SECONDS;
455 >        case MINUTES: return TimeUnit.MINUTES;
456 >        case HOURS:   return TimeUnit.HOURS;
457 >        case DAYS:    return TimeUnit.DAYS;
458 >        default:
459 >            throw new IllegalArgumentException(
460 >                "No TimeUnit equivalent for " + chronoUnit);
461 >        }
462 >    }
463 >
464   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines