1717package org .apache .commons .io ;
1818
1919import java .time .Duration ;
20+ import java .time .Instant ;
2021
2122/**
2223 * Monitors a thread, interrupting it if it reaches the specified timeout.
@@ -118,21 +119,21 @@ public void run() {
118119 * Sleeps for a guaranteed minimum duration unless interrupted.
119120 *
120121 * This method exists because Thread.sleep(100) can sleep for 0, 70, 100 or 200ms or anything else
121- * it deems appropriate. Read the docs on Thread. sleep for further interesting details.
122+ * it deems appropriate. Read {@link Thread# sleep()} for further interesting details.
122123 *
123124 * @param duration the sleep duration.
124125 * @throws InterruptedException if interrupted
125126 */
126127 private static void sleep (final Duration duration ) throws InterruptedException {
127- // Ignore nanos for now.
128- final long millis = duration .toMillis ();
129- final long finishAtMillis = System .currentTimeMillis () + millis ;
130- long remainingMillis = millis ;
128+ final Instant finishInstant = Instant .now ().plus (duration );
129+ Duration remainingDuration = duration ;
131130 do {
132- Thread .sleep (remainingMillis );
133- remainingMillis = finishAtMillis - System . currentTimeMillis ( );
134- } while (remainingMillis > 0 );
131+ Thread .sleep (remainingDuration . toMillis (), getNanosOfMiili ( remainingDuration ) );
132+ remainingDuration = Duration . between ( Instant . now (), finishInstant );
133+ } while (! remainingDuration . isNegative () );
135134 }
136135
137-
136+ private static int getNanosOfMiili (final Duration duration ) {
137+ return duration .getNano () % 1_000_000 ;
138+ }
138139}
0 commit comments