Set runtime limit for method in java

I have a method that returns String, is it possible that after some time treshold will be excedeed so that this method returns a specific string?

+8
java
source share
4 answers

The Guava library has a very nice TimeLimiter that allows you to do this using any method defined by the interface. It can generate proxies for your object, which has a "built-in" timeout.

+14
source share

In the past, I did something similar when I created an external process using Runtime.getRuntime().exec(command) . I think you could do something like this in your method:

 Timer timer = new Timer(true); InterruptTimerTask interruptTimerTask = new InterruptTimerTask(Thread.currentThread()); timer.schedule(interruptTimerTask, waitTimeout); try { // put here the portion of code that may take more than "waitTimeout" } catch (InterruptedException e) { log.error("timeout exeeded); } finally { timer.cancel(); } 

and here is InterruptTimerTask

 /* * A TimerTask that interrupts the specified thread when run. */ protected class InterruptTimerTask extends TimerTask { private Thread theTread; public InterruptTimerTask(Thread theTread) { this.theTread = theTread; } @Override public void run() { theTread.interrupt(); } } 
+9
source share

As pointed out by @MarcoS

I found that a timeout does not occur if the method blocks something and does not free up CPU time for the timer. Then the timer cannot start a new thread. Therefore, I will slightly change the initial flow and immediately fall asleep inside.

  InterruptTimerTaskAddDel interruptTimerTask = new InterruptTimerTaskAddDel( Thread.currentThread(),timeout_msec); timer.schedule(interruptTimerTask, 0); /* * A TimerTask that interrupts the specified thread when run. */ class InterruptTimerTaskAddDel extends TimerTask { private Thread theTread; private long timeout; public InterruptTimerTaskAddDel(Thread theTread,long i_timeout) { this.theTread = theTread; timeout=i_timeout; } @Override public void run() { try { Thread.currentThread().sleep(timeout); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(System.err); } theTread.interrupt(); } } 
+1
source share

You can use AOP and @Timeable annotation from jcabi- aspects (I'm a developer):

 @Timeable(limit = 1, unit = TimeUnit.SECONDS) String load(String resource) { while (true) { if (Thread.currentThread.isInterrupted()) { throw new IllegalStateException("time out"); } // execution as usual } } 

When the time limit is reached, your thread will receive the interrupted() flag set to true , and your task will correctly handle this situation and stop execution.

Also flag this blog post: http://www.yegor256.com/2014/06/20/limit-method-execution-time.html

+1
source share

All Articles