Limit Java Method Execution Time
Annotate your methods with @Timeable
annotation and every time their execution takes more than the allowed time, 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.
It is 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? 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 to know how to integrate it into your pom.xml
.
This blog post gives more details about the internal implementation of the mechanism.