Fork me on GitHub jcabi

24-Oct-2013 0.12

Limit Java Method Execution Time

Annotate your methods with @Timeable annotation and every time their execution takes more than allowed their thread will be interrupted:

public class Resource {
  @Timeable(limit = 5, unit = TimeUnit.SECONDS)
  public String load(URL url) {
    return url.openConnection().getContent();
  }
}

The thread running this method will be terminated if it takes more than five seconds.

Important to note that in Java 1.5+ it is impossible to force thread termination: Why Are Thread.stop, Thread.suspend, Thread.resume and Runtime.runFinalizersOnExit Deprecated?. Thus, we can't just call Thread.stop(), when a thread is over a specified time limit. The best thing we can do is to call Thread#interrupt() and hope that the thread itself is checking its Thread#isInterrupted() status. If you want to design your long-running methods in a way that @Timeable can terminate them, embed a checker into your most intessively used place, for example:

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

The mechanism is implemented with AOP/AspectJ. Read how to integrate it into your pom.xml.

Copyright © 2012-2013 jcabi.com, All Rights Reserved. Privacy Policy.

site is built by Apache Maven