Given a Clock, an Instant and the current Thread, is there already some (utility) method in the Java libraries that makes the current thread sleep until the given clock reaches the instant?
Something like
public static void sleepUntil(Instant instant, Clock clock)
throws InterruptedException;
?
I need this in a test setting where I am working with a custom slowed-down clock.
I know that it is easy to implement, but I would prefer a standard solution if available (but didn't find it so far).
To make a thread sleep for 1 minute, you do something like this: TimeUnit. MINUTES. sleep(1);
Thread. sleep() method can be used to pause the execution of current thread for specified time in milliseconds.
Thread. sleep causes the current thread to suspend execution for a specified period. This is an efficient means of making processor time available to the other threads of an application or other applications that might be running on a computer system.
Wait() method releases lock during Synchronization. Sleep() method does not release the lock on object during Synchronization. Wait() should be called only from Synchronized context. There is no need to call sleep() from Synchronized context.
First of all, Clock
is a really simple class with little implementation and few uses in the standard API. SystemClock
, OffsetClock
and TickClock
are examples in the same file. So the answer seems to be No, it is not in the default API.
If you are given the "slowed-down clock" and may not modify it to add the desired sleepUntil()
-code, and it is slowed down by a fixed amount, you could do something like
public static void sleepUntil(Instant instant, Clock clock)
throws InterruptedException {
Instant now = Instant.now(clock);
long duration = now.until(instant, ChronoUnit.MILLIS);
long testSleep
= ( duration < 10000 )? (duration / 10) : 1000;
long start = clock.millis();
Thread.sleep(testSleep);
long stop = clock.millis();
double clockskew = (stop - start) / testSleep;
now = Instant.now(clock);
Thread.sleep(now.until(instant, ChronoUnit.MILLIS) * clockskew);
}
This first does a test run to determine the clock skew, then sleeps an adjusted duration.
(Maybe you need to adjust the instant in sleep
to adjust to the other clock. Post your clock code if you wish to have it tested/adjusted.)
In my case, I was needed to wait for a particular time. My solution.
long expirationTime = System.currentTimeMillis() + 60_000;
Thread.sleep(expirationTime - System.currentTimeMillis());
Another way is to do it with do-while
but actually, I couldn't see its advantages.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With