Set running time limit on a method in java

后端 未结 4 776
一向
一向 2020-12-10 06:23

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?

4条回答
  •  情深已故
    2020-12-10 06:58

    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

提交回复
热议问题