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 ?

有帮助吗?

解决方案

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) {
  ...
...

其他提示

In cause of ExecutionException instance, I suppose.

In the ExecutionException catch block: e.getCause()

https://docs.oracle.com/javase/6/docs/api/java/lang/Throwable.html#getCause

thread.sleep(x millisecods) will stop the thread for x milliseconds, then it will resume. The other way to do it is to call thread.wait(x) (with a timeout value for x) and then call thread.notify() to "wake" the sleeping thread.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top