Class TimeLimiter


  • public class TimeLimiter
    extends Object
    Imposes a time limit on method calls.
    • Constructor Detail

      • TimeLimiter

        public TimeLimiter()
    • Method Detail

      • callWithTimeout

        public static <T> T callWithTimeout​(Callable<T> callable,
                                            long timeoutDuration,
                                            TimeUnit timeoutUnit)
                                     throws Exception
        Invokes a specified Callable with the specified time limit. If the target method call finishes before the limit is reached, the return value or the exception is propagated. If the time limit is reached, we attempt to abort the call, and throw a TimeoutException to the caller.
        Type Parameters:
        T - the type of the task's result
        Parameters:
        callable - the Callable to execute
        timeoutDuration - with timeoutUnit, the maximum length of time to wait
        timeoutUnit - with timeoutDuration, the maximum length of time to wait
        Returns:
        the result returned by the Callable
        Throws:
        Exception - if the time limit is reached, the thread is interrupted, or an exception is thrown during execution.
      • runWithTimeout

        public void runWithTimeout​(Runnable runnable,
                                   long timeoutDuration,
                                   TimeUnit timeoutUnit)
                            throws Exception
        Invokes a specified Runnable with the specified time limit. If the target method call finishes before the limit is reached, the return value or the exception is propagated. If the time limit is reached, we attempt to abort the call, and throw a TimeoutException to the caller.
        Parameters:
        runnable - the Runnable to execute
        timeoutDuration - with timeoutUnit, the maximum length of time to wait
        timeoutUnit - with timeoutDuration, the maximum length of time to wait
        Throws:
        Exception - if the time limit is reached, the thread is interrupted, or an exception is thrown during execution.