/** * Waits for an operation to return a non-null value with a specified timeout. * * @param description the description of this operation * @param operation the operation * @param options the options to use * @param <T> the type of the return value * @throws TimeoutException if the function times out while waiting to get a non-null value * @return the first non-null value generated by the operation */ public static <T> T waitForResult(String description, Supplier<T> operation, WaitForOptions options) throws InterruptedException, TimeoutException { T t; long start = System.currentTimeMillis(); int interval = options.getInterval(); int timeout = options.getTimeoutMs(); while ((t = operation.get()) == null) { if (timeout != WaitForOptions.NEVER && System.currentTimeMillis() - start > timeout) { throw new TimeoutException("Timed out waiting for " + description + " options: " + options); } Thread.sleep(interval); } return t; }
/** * Tests getting and setting fields. */ @Test public void fields() { Random random = new Random(); int interval = random.nextInt(); int timeout = random.nextInt(); WaitForOptions options = WaitForOptions.defaults(); options.setInterval(interval); options.setTimeoutMs(timeout); Assert.assertEquals(interval, options.getInterval()); Assert.assertEquals(timeout, options.getTimeoutMs()); }
@Test public void defaults() { WaitForOptions options = WaitForOptions.defaults(); Assert.assertEquals(WaitForOptions.DEFAULT_INTERVAL, options.getInterval()); Assert.assertEquals(WaitForOptions.NEVER, options.getTimeoutMs()); }
/** * Waits for an operation to return a non-null value with a specified timeout. * * @param description the description of this operation * @param operation the operation * @param options the options to use * @param <T> the type of the return value * @return the return value, null if it times out */ public static <T> T waitForResult(String description, Function<Void, T> operation, WaitForOptions options) { T t; long start = System.currentTimeMillis(); int interval = options.getInterval(); int timeout = options.getTimeoutMs(); while ((t = operation.apply(null)) == null) { if (timeout != WaitForOptions.NEVER && System.currentTimeMillis() - start > timeout) { throw new RuntimeException("Timed out waiting for " + description + " options: " + options); } CommonUtils.sleepMs(interval); } return t; }
WaitForOptions options) { long start = System.currentTimeMillis(); int interval = options.getInterval(); int timeout = options.getTimeoutMs(); while (!condition.apply(null)) {