@Test public void shouldUseCallWithTimeout() throws Exception { TimeLimiter timeLimiter = new SimpleTimeLimiter(); long start = System.nanoTime(); String result = timeLimiter.callWithTimeout( () -> doSomeHeavyWeightOperation(), ENOUGH_MS, MILLISECONDS, true); assertEquals("done", result); TimeOutAssertion.assertTheCallTookBetween(start, DELAY_MS, ENOUGH_MS); }
/** * Timing out after the specified time limit with {@link TimeLimiter} * * @param timeLimiter * @param duration * @param timeUnit * @return */ public Retryer<R> timeout(final TimeLimiter timeLimiter, final long duration, final TimeUnit timeUnit) { return withTimelimiter(new AttemptTimelimit<R>() { @Override public R call(Callable<R> callable) throws Exception { return checkNotNull(timeLimiter, "TimeLimiter cannot be null") .callWithTimeout(callable, duration, checkNotNull(timeUnit), true); } }); }
@Test public void shouldUseProxy() throws Exception { TimeLimiter timeLimiter = new SimpleTimeLimiter(); long start = System.nanoTime(); HeavyOperation target = () -> doSomeHeavyWeightOperation(); HeavyOperation proxy = timeLimiter.newProxy(target, HeavyOperation.class, ENOUGH_MS, MILLISECONDS); assertEquals("done", proxy.doHeavyWeightOperation()); TimeOutAssertion.assertTheCallTookBetween(start, DELAY_MS, ENOUGH_MS); }
public static <T> T tryWith(long timeoutDuration, TimeUnit timeoutUnit, Callable<T> callable) { try { TimeLimiter limiter = new SimpleTimeLimiter(); //noinspection unchecked Callable<T> proxy = limiter.newProxy(callable, Callable.class, timeoutDuration, timeoutUnit); return proxy.call(); } catch (Exception e) { throw uncheckedException().apply(e); } }
public static void tryWith(long timeoutDuration, TimeUnit timeoutUnit, Effect effect) { try { TimeLimiter limiter = new SimpleTimeLimiter(); //noinspection unchecked Effect proxy = limiter.newProxy(effect, Effect.class, timeoutDuration, timeoutUnit); proxy.cause(); } catch (Exception e) { throw uncheckedException().apply(e); } }
public static TimeLimiter create() { return SimpleTimeLimiter.create(new NewRequestThreadExecutorService()); }
private static <T> T timeLimited(T target, Class<T> clazz, Duration timeout, ExecutorService executor) { TimeLimiter limiter = new SimpleTimeLimiter(executor); return limiter.newProxy(target, clazz, timeout.toMillis(), MILLISECONDS); }
DecoratedCallableFunction(TimeLimiter limiter) { this.limiter = limiter; }
@VisibleForTesting DecoratedCallableBuilder(TimeLimiter limiter) { this.limiter = limiter; }