Search code examples
javathreadpooldelay

How to wait for 2 minutes for method to complete, but then Exit and continue?


How to wait for 2 minutes for method to complete, but if it does not complete then Exit and continue?

I want to wait for 2 minutes for method to complete, but if it does not complete in 2 minutes then Exit execution and continue ahead.


Solution

  • With the help of Executor and Futures I think this could help

        ExecutorService executor = Executors.newCachedThreadPool();
    
        Future<String> future = executor.submit( new Callable<String>() {
            public String call() throws Exception {
                return someVeryLengthMethod();
            }});
    
        String result = null;
        try {
            result = future.get(2, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            // Somebody interrupted us
        } catch (ExecutionException e) {
            // Something went wring, handle it...
        } catch (TimeoutException e) {
            // Too long time
            future.cancel(true);
        }
        // Continue with what we have...
    

    This will wait for the answer a specified time, and if the result is not available within that time the future is cancelled (which may or may not actually stop the execution of that task), and the code can continue.