    001/*
    002 * Licensed to the Apache Software Foundation (ASF) under one or more
    003 * contributor license agreements.  See the NOTICE file distributed with
    004 * this work for additional information regarding copyright ownership.
    005 * The ASF licenses this file to You under the Apache License, Version 2.0
    006 * (the "License"); you may not use this file except in compliance with
    007 * the License.  You may obtain a copy of the License at
    008 *
    009 *      http://www.apache.org/licenses/LICENSE-2.0
    010 *
    011 * Unless required by applicable law or agreed to in writing, software
    012 * distributed under the License is distributed on an "AS IS" BASIS,
    013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    014 * See the License for the specific language governing permissions and
    015 * limitations under the License.
    016 */
    017package org.apache.commons.io;
    018
    019import java.time.Duration;
    020import java.time.Instant;
    021
    022/**
    023 * Helps work with threads.
    024 *
    025 * @since 2.12.0
    026 */
    027public final class ThreadUtils {
    028
    029    private static int getNanosOfMilli(final Duration duration) {
    030        return duration.getNano() % 1_000_000;
    031    }
    032
    033    /**
    034     * Sleeps for a guaranteed minimum duration unless interrupted.
    035     * <p>
    036     * This method exists because Thread.sleep(100) can sleep for 0, 70, 100 or 200ms or anything else it deems appropriate. Read
    037     * {@link Thread#sleep(long, int)}} for further interesting details.
    038     * </p>
    039     *
    040     * @param duration the sleep duration.
    041     * @throws InterruptedException if interrupted.
    042     * @see Thread#sleep(long, int)
    043     */
    044    public static void sleep(final Duration duration) throws InterruptedException {
    045        // Using this method avoids depending on the vagaries of the precision and accuracy of system timers and schedulers.
    046        try {
    047            // Use the JVM elapsed time, avoids issues with DST changes and manual OS time changes.
    048            final long nanoStart = System.nanoTime();
    049            final long finishNanos = nanoStart + duration.toNanos(); // toNanos(): Possible ArithmeticException, otherwise wrap around OK.
    050            Duration remainingDuration = duration;
    051            long nowNano;
    052            do {
    053                Thread.sleep(remainingDuration.toMillis(), getNanosOfMilli(remainingDuration));
    054                nowNano = System.nanoTime();
    055                remainingDuration = Duration.ofNanos(finishNanos - nowNano);
    056            } while (nowNano - finishNanos < 0); // handles wrap around, see Thread#sleep(long, int).
    057        } catch (final ArithmeticException e) {
    058            // Use the current time
    059            final Instant finishInstant = Instant.now().plus(duration);
    060            Duration remainingDuration = duration;
    061            do {
    062                Thread.sleep(remainingDuration.toMillis(), getNanosOfMilli(remainingDuration));
    063                remainingDuration = Duration.between(Instant.now(), finishInstant);
    064            } while (!remainingDuration.isNegative());
    065        }
    066    }
    067
    068    /**
    069     * Make private in 3.0.
    070     *
    071     * @deprecated TODO Make private in 3.0.
    072     */
    073    @Deprecated
    074    public ThreadUtils() {
    075        // empty
    076    }
    077}