Search code examples
javajava.util.concurrentconcurrent-programming

calling a blocking method call with timeout in java


I want to call a method in java which blocks for some reason. I want to wait for the method for X minutes and then I want to stop that method.

I have read one solution here on StackOverflow which gave me a first quick start. I am writing that here :-

ExecutorService executor = Executors.newCachedThreadPool();
    Callable<Object> task = new Callable<Object>() {
       public Object call() {
          return something.blockingMethod();
       }
    };
    Future<Object> future = executor.submit(task);
    try {
       Object result = future.get(5, TimeUnit.SECONDS); 
    } catch (TimeoutException ex) {
       // handle the timeout
    } catch (InterruptedException e) {
       // handle the interrupts
    } catch (ExecutionException e) {
       // handle other exceptions
    } finally {
       future.cancel(); // may or may not desire this
    }

But now my problem is, my function can throw some Exception which I have to catch and do some task accordingly. So if in code the function blockingMethod() thorws some exception how do I catch them in Outer class ?


Solution

  • You have everything set up to do that in the code you provide. Just replace

    // handle other exceptions
    

    with your exception handling.
    If you need to get your specific Exception you get it with:

    Throwable t = e.getCause();
    

    And to differentiate between your Exceptions you can do like this:

    if (t instanceof MyException1) {
      ...
    } else if (t instanceof MyException2) {
      ...
    ...