Skip to content

Instantly share code, notes, and snippets.

@DaHoC
Created January 6, 2023 13:01
Show Gist options
  • Save DaHoC/ec3892f046a750953e8155b2287a0d89 to your computer and use it in GitHub Desktop.
Save DaHoC/ec3892f046a750953e8155b2287a0d89 to your computer and use it in GitHub Desktop.
AsyncWaitForConditionWithCountDownLatch
/**
* Generic method that properly awaits a given condition to become true within a given timeout.
* This is superior to {@code sleep()} methods because it returns early when the condition is met.
*
* @param boolSupplier the supplier for evaluating the condition, should return {@code true} if condition is met, {@code false} otherwise
* @param timeout timeout number
* @param timeUnit timeout unit
* @return {@code true} if condition is met within given time, {@code false} otherwise
*/
private boolean waitForCondition(final BooleanSupplier boolSupplier, long timeout, final TimeUnit timeUnit) {
final CountDownLatch conditionMetLatch = new CountDownLatch(1);
final Runnable checkConditionMetRunner = () -> {
do {
if (boolSupplier.getAsBoolean()) {
conditionMetLatch.countDown();
}
} while (conditionMetLatch.getCount() != 0 && !Thread.currentThread().isInterrupted());
};
final ExecutorService executor = Executors.newSingleThreadExecutor();
try {
executor.execute(checkConditionMetRunner);
return conditionMetLatch.await(timeout, timeUnit);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return false;
} finally {
executor.shutdownNow();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment