Created
January 6, 2023 13:01
-
-
Save DaHoC/ec3892f046a750953e8155b2287a0d89 to your computer and use it in GitHub Desktop.
AsyncWaitForConditionWithCountDownLatch
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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