Search code examples
javatimeexecute

How to set up time for a execute some method in java?


I have some method called exampleMethod. When I call this method (it work with network...) some times, when is network slow it takes a long time...

How can I set up some max time for execute?

For example 10s.

Like this...

try {
      exampleMethod();
} catch(Exeption e) {
      LoggError("I was to slow");
}

I hope, you understand me, thank you for any help.,


Solution

  • You can use a ExecutorService, set a timeout value and cancel the future if the timeout is passed in order to request a thread interruption :

        ExecutorService executorService = Executors.newSingleThreadExecutor();
        Future<?> future = null;
        try {
            Runnable r = new Runnable() {
                @Override
                public void run() {
                    while (true) {
                        // it the timeout happens, the thread should be interrupted. Check it to let the thread terminates.
                        if (Thread.currentThread().isInterrupted()) {
                            return;
                        }
                        exampleMethod();
                    }
    
                }
            };
    
            future = executorService.submit(r);
            future.get(10, TimeUnit.SECONDS);
        }
    
        // time is passed
        catch (final TimeoutException e) {
            System.out.println("I was to slow");
            // you cancel the future
            future.cancel(true);
        }
        // other exceptions
        catch (Exception e) {
            e.printStackTrace();
        } finally {
            executorService.shutdown();
        }
    }