I have a method that returns a String, is it possible that after a certain time treshold is excedeed fot that method to return some specific string?
You can use AOP and a @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 time limit is reached your thread will get interrupted() flag set to true and it's your job to handle this situation correctly and to stop execution.
Also, check this blog post: http://www.yegor256.com/2014/06/20/limit-method-execution-time.html