1 /* 2 * Licensed to the Apache Software Foundation (ASF) under one or more 3 * contributor license agreements. See the NOTICE file distributed with 4 * this work for additional information regarding copyright ownership. 5 * The ASF licenses this file to You under the Apache License, Version 2.0 6 * (the "License"); you may not use this file except in compliance with 7 * the License. You may obtain a copy of the License at 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 */ 17 18 package org.apache.commons.lang3.time; 19 20 import java.time.Duration; 21 import java.time.Instant; 22 import java.time.temporal.ChronoUnit; 23 import java.time.temporal.Temporal; 24 import java.util.Objects; 25 import java.util.concurrent.TimeUnit; 26 27 import org.apache.commons.lang3.LongRange; 28 import org.apache.commons.lang3.ObjectUtils; 29 import org.apache.commons.lang3.function.FailableBiConsumer; 30 import org.apache.commons.lang3.function.FailableConsumer; 31 import org.apache.commons.lang3.function.FailableRunnable; 32 import org.apache.commons.lang3.math.NumberUtils; 33 34 /** 35 * Utilities for {@link Duration}. 36 * 37 * @since 3.12.0 38 */ 39 public class DurationUtils { 40 41 /** 42 * An Integer Range that accepts Longs. 43 */ 44 static final LongRange LONG_TO_INT_RANGE = LongRange.of(NumberUtils.LONG_INT_MIN_VALUE, NumberUtils.LONG_INT_MAX_VALUE); 45 46 /** 47 * Accepts the function with the duration as a long milliseconds and int nanoseconds. 48 * 49 * @param <T> The function exception. 50 * @param consumer Accepting function. 51 * @param duration The duration to pick apart. 52 * @throws T See the function signature. 53 * @see StopWatch 54 */ 55 @SuppressWarnings("boxing") // boxing unavoidable 56 public static <T extends Throwable> void accept(final FailableBiConsumer<Long, Integer, T> consumer, final Duration duration) 57 throws T { 58 if (consumer != null && duration != null) { 59 consumer.accept(duration.toMillis(), getNanosOfMilli(duration)); 60 } 61 } 62 63 /** 64 * Gets the nanosecond part of a Duration converted to milliseconds. 65 * <p> 66 * Handy when calling an API that takes a long of milliseconds and an int of nanoseconds. For example, 67 * {@link Object#wait(long, int)} and {@link Thread#sleep(long, int)}. 68 * </p> 69 * <p> 70 * Note that is this different from {@link Duration#getNano()} because a duration are seconds and nanoseconds. 71 * </p> 72 * 73 * @param duration The duration to query. 74 * @return nanoseconds between 0 and 999,999. 75 * @deprecated Use {@link #getNanosOfMilli(Duration)}. 76 */ 77 @Deprecated 78 public static int getNanosOfMiili(final Duration duration) { 79 return getNanosOfMilli(duration); 80 } 81 82 /** 83 * Gets the nanosecond part of a Duration converted to milliseconds. 84 * <p> 85 * Handy when calling an API that takes a long of milliseconds and an int of nanoseconds. For example, 86 * {@link Object#wait(long, int)} and {@link Thread#sleep(long, int)}. 87 * </p> 88 * <p> 89 * Note that is this different from {@link Duration#getNano()} because a duration are seconds and nanoseconds. 90 * </p> 91 * 92 * @param duration The duration to query. 93 * @return nanoseconds between 0 and 999,999. 94 * @since 3.13.0 95 */ 96 public static int getNanosOfMilli(final Duration duration) { 97 return zeroIfNull(duration).getNano() % 1_000_000; 98 } 99 100 /** 101 * Tests whether the given Duration is positive (>0). 102 * 103 * @param duration the value to test 104 * @return whether the given Duration is positive (>0). 105 */ 106 public static boolean isPositive(final Duration duration) { 107 return !duration.isNegative() && !duration.isZero(); 108 } 109 110 private static <E extends Throwable> Instant now(final FailableConsumer<Instant, E> nowConsumer) throws E { 111 final Instant start = Instant.now(); 112 nowConsumer.accept(start); 113 return start; 114 } 115 116 /** 117 * Runs the lambda and returns the duration of its execution. 118 * 119 * @param <E> The type of exception throw by the lambda. 120 * @param consumer What to execute. 121 * @return The Duration of execution. 122 * @throws E thrown by the lambda. 123 * @see StopWatch 124 * @since 3.13.0 125 */ 126 public static <E extends Throwable> Duration of(final FailableConsumer<Instant, E> consumer) throws E { 127 return since(now(consumer::accept)); 128 } 129 130 /** 131 * Runs the lambda and returns the duration of its execution. 132 * 133 * @param <E> The type of exception throw by the lambda. 134 * @param runnable What to execute. 135 * @return The Duration of execution. 136 * @throws E thrown by the lambda. 137 * @see StopWatch 138 * @since 3.13.0 139 */ 140 public static <E extends Throwable> Duration of(final FailableRunnable<E> runnable) throws E { 141 return of(start -> runnable.run()); 142 } 143 144 /** 145 * Computes the Duration between a start instant and now. 146 * 147 * @param startInclusive the start instant, inclusive, not null. 148 * @return a {@link Duration}, not null. 149 * @since 3.13.0 150 */ 151 public static Duration since(final Temporal startInclusive) { 152 return Duration.between(startInclusive, Instant.now()); 153 } 154 155 /** 156 * Converts a {@link TimeUnit} to a {@link ChronoUnit}. 157 * 158 * @param timeUnit A non-null TimeUnit. 159 * @return The corresponding ChronoUnit. 160 */ 161 static ChronoUnit toChronoUnit(final TimeUnit timeUnit) { 162 // TODO when using Java >= 9: Use TimeUnit.toChronoUnit(). 163 switch (Objects.requireNonNull(timeUnit)) { 164 case NANOSECONDS: 165 return ChronoUnit.NANOS; 166 case MICROSECONDS: 167 return ChronoUnit.MICROS; 168 case MILLISECONDS: 169 return ChronoUnit.MILLIS; 170 case SECONDS: 171 return ChronoUnit.SECONDS; 172 case MINUTES: 173 return ChronoUnit.MINUTES; 174 case HOURS: 175 return ChronoUnit.HOURS; 176 case DAYS: 177 return ChronoUnit.DAYS; 178 default: 179 throw new IllegalArgumentException(timeUnit.toString()); 180 } 181 } 182 183 /** 184 * Converts an amount and TimeUnit into a Duration. 185 * 186 * @param amount the amount of the duration, measured in terms of the unit, positive or negative 187 * @param timeUnit the unit that the duration is measured in, must have an exact duration, not null 188 * @return a Duration. 189 */ 190 public static Duration toDuration(final long amount, final TimeUnit timeUnit) { 191 return Duration.of(amount, toChronoUnit(timeUnit)); 192 } 193 194 /** 195 * Converts a Duration to milliseconds bound to an int (instead of a long). 196 * <p> 197 * Handy for low-level APIs that take millisecond timeouts in ints rather than longs. 198 * </p> 199 * <ul> 200 * <li>If the duration milliseconds are greater than {@link Integer#MAX_VALUE}, then return 201 * {@link Integer#MAX_VALUE}.</li> 202 * <li>If the duration milliseconds are lesser than {@link Integer#MIN_VALUE}, then return 203 * {@link Integer#MIN_VALUE}.</li> 204 * </ul> 205 * 206 * @param duration The duration to convert, not null. 207 * @return int milliseconds. 208 */ 209 public static int toMillisInt(final Duration duration) { 210 Objects.requireNonNull(duration, "duration"); 211 // intValue() does not do a narrowing conversion here 212 return LONG_TO_INT_RANGE.fit(Long.valueOf(duration.toMillis())).intValue(); 213 } 214 215 /** 216 * Returns the given non-null value or {@link Duration#ZERO} if null. 217 * 218 * @param duration The duration to test. 219 * @return The given duration or {@link Duration#ZERO}. 220 */ 221 public static Duration zeroIfNull(final Duration duration) { 222 return ObjectUtils.defaultIfNull(duration, Duration.ZERO); 223 } 224 225 /** 226 * Make private in 4.0. 227 * 228 * @deprecated TODO Make private in 4.0. 229 */ 230 @Deprecated 231 public DurationUtils() { 232 // empty 233 } 234 }