    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        final Instant finishInstant = Instant.now().plus(duration);
    047        Duration remainingDuration = duration;
    048        do {
    049            Thread.sleep(remainingDuration.toMillis(), getNanosOfMilli(remainingDuration));
    050            remainingDuration = Duration.between(Instant.now(), finishInstant);
    051        } while (!remainingDuration.isNegative());
    052    }
    053
    054}