• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 package org.apache.commons.io;
18 
19 import java.time.Duration;
20 import java.time.Instant;
21 
22 /**
23  * Helps work with threads.
24  *
25  * @since 2.12.0
26  */
27 public class ThreadUtils {
28 
getNanosOfMilli(final Duration duration)29     static int getNanosOfMilli(final Duration duration) {
30         return duration.getNano() % 1_000_000;
31     }
32 
33     /**
34      * Sleeps for a guaranteed minimum duration unless interrupted.
35      *
36      * This method exists because Thread.sleep(100) can sleep for 0, 70, 100 or 200ms or anything else it deems appropriate.
37      * Read {@link Thread#sleep(long, int)}} for further interesting details.
38      *
39      * TODO The above needs confirmation now that we've been on Java 8 for a while.
40      *
41      * @param duration the sleep duration.
42      * @throws InterruptedException if interrupted.
43      */
sleep(final Duration duration)44     public static void sleep(final Duration duration) throws InterruptedException {
45         final Instant finishInstant = Instant.now().plus(duration);
46         Duration remainingDuration = duration;
47         do {
48             Thread.sleep(remainingDuration.toMillis(), getNanosOfMilli(remainingDuration));
49             remainingDuration = Duration.between(Instant.now(), finishInstant);
50         } while (!remainingDuration.isNegative());
51     }
52 
53 }
54