-
Notifications
You must be signed in to change notification settings - Fork 0
Awaitility
Le Thanh NGUYEN edited this page Jan 19, 2016
·
1 revision
A sort of Awaitility - Waiting until get an object from Supplier (java 8) with an interval and a timeout
@SuppressWarnings("unchecked")
private <T> T awaitUntil(long timeoutMillis, Supplier<T> supplier, long intervalMillis) throws InterruptedException {
final Class<T> clazz = (Class<T>) ((ParameterizedType) supplier.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
final T[] arr = (T[]) Array.newInstance(clazz, 1);
final boolean[] timeouts = new boolean[1];
final ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.execute(() -> {
arr[0] = supplier.get();
while (arr[0] == null && !timeouts[0]) {
try {
Thread.sleep(intervalMillis);
} catch (InterruptedException e) {
//
}
arr[0] = supplier.get();
}
});
executorService.shutdown();
executorService.awaitTermination(timeoutMillis, TimeUnit.MILLISECONDS);
timeouts[0] = true;
return arr[0];
}