2

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.,

rilav
  • 23
  • 2
  • It depends on what your method is doing. Usually blocking operations will allow a timeout or interruption. – shmosel Jan 22 '17 at 11:13
  • Possible duplicate of [How to timeout a thread](http://stackoverflow.com/questions/2275443/how-to-timeout-a-thread) – tucuxi Jan 22 '17 at 11:14
  • Sure, can I wrote some own timeout wraper? It is possible? – rilav Jan 22 '17 at 11:15

1 Answers1

0

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();
    }
}
davidxxx
  • 125,838
  • 23
  • 214
  • 215