/** * Runs the supplied {@code action} until {@code stopCondition} is met or timeout. */ public static void runWithTimeout(ThrowingAction action, BooleanSupplier stopCondition, long timeout, TimeUnit unit) throws Exception { final long waitTime = unit.toNanos(timeout); final long startTime = System.nanoTime(); while (!stopCondition.getAsBoolean()) { action.run(); if (System.nanoTime() - startTime >= waitTime) { throw new TimeoutException("Stop condition was not met after " + unit.toSeconds(timeout) + " seconds."); } } }
/** * Executes the passed action, retrying if the operation is interrupted. Once the interruptible * completes, the current thread will be re-interrupted, if the original operation was interrupted. */ public static void doExUninterruptibly(ThrowingAction interruptible) throws Exception { boolean interrupted = false; try { while (true) { try { interruptible.run(); break; } catch (InterruptedException e) { // NOSONAR- we will re-interrupt the thread during unwind interrupted = true; } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } }
/** * Runs the supplied action, after suspending any pending interruption. An error will be logged if * the action is itself interrupted. */ public static void runUninterruptible(ThrowingAction action) throws Exception { boolean interrupted = Thread.interrupted(); try { action.run(); if (Thread.interrupted()) { throw new InterruptedException(); } } catch (InterruptedException e) { LOGGER.error("uninterruptible action {} was interrupted!", action, e); interrupted = true; } finally { if (interrupted) { Thread.currentThread().interrupt(); } } }
public void loopUntilExhausted(ThrowingAction action, long delay, TimeUnit delayUnit) throws Exception { while (!elapsed()) { action.run(); if (elapsed(delayUnit) < delay) { break; } sleep(delay, delayUnit); } }