Search in sources :

Example 1 with Timeout

use of org.eclipse.microprofile.faulttolerance.Timeout in project Payara by payara.

the class TimeoutInterceptor method timeout.

/**
 * Proceeds the given invocation context with Timeout semantics.
 * @param invocationContext The invocation context to proceed.
 * @return The result of the invocation context.
 * @throws Exception If the invocation context execution throws an exception
 */
private Object timeout(InvocationContext invocationContext) throws Exception {
    Object proceededInvocationContext = null;
    Timeout timeout = FaultToleranceCdiUtils.getAnnotation(beanManager, Timeout.class, invocationContext);
    Config config = null;
    try {
        config = ConfigProvider.getConfig();
    } catch (IllegalArgumentException ex) {
        logger.log(Level.INFO, "No config could be found", ex);
    }
    long value = (Long) FaultToleranceCdiUtils.getOverrideValue(config, Timeout.class, "value", invocationContext, Long.class).orElse(timeout.value());
    ChronoUnit unit = (ChronoUnit) FaultToleranceCdiUtils.getOverrideValue(config, Timeout.class, "unit", invocationContext, ChronoUnit.class).orElse(timeout.unit());
    Future timeoutFuture = null;
    ThreadLocal<Boolean> timedOut = new ThreadLocal<>();
    timedOut.set(false);
    long timeoutMillis = Duration.of(value, unit).toMillis();
    long timeoutTime = System.currentTimeMillis() + timeoutMillis;
    try {
        timeoutFuture = startTimeout(timeoutMillis, timedOut);
        proceededInvocationContext = invocationContext.proceed();
        stopTimeout(timeoutFuture);
        if (System.currentTimeMillis() > timeoutTime || timedOut.get()) {
            logger.log(Level.FINE, "Execution timed out");
            throw new TimeoutException();
        }
    } catch (Exception ex) {
        stopTimeout(timeoutFuture);
        throw ex;
    }
    return proceededInvocationContext;
}
Also used : Timeout(org.eclipse.microprofile.faulttolerance.Timeout) Config(org.eclipse.microprofile.config.Config) NamingException(javax.naming.NamingException) TimeoutException(org.eclipse.microprofile.faulttolerance.exceptions.TimeoutException) Future(java.util.concurrent.Future) ChronoUnit(java.time.temporal.ChronoUnit) TimeoutException(org.eclipse.microprofile.faulttolerance.exceptions.TimeoutException)

Aggregations

ChronoUnit (java.time.temporal.ChronoUnit)1 Future (java.util.concurrent.Future)1 NamingException (javax.naming.NamingException)1 Config (org.eclipse.microprofile.config.Config)1 Timeout (org.eclipse.microprofile.faulttolerance.Timeout)1 TimeoutException (org.eclipse.microprofile.faulttolerance.exceptions.TimeoutException)1