Java – how to check whether the function execution exceeds the specified number of seconds?

If it takes more than 3 seconds, I want to time out a function

long startTime = System.currentTimeMillis();
getStaticJsonResponse("build","post");
long finishTime = System.currentTimeMillis();
long elapsedTime = finishTime - startTime / 1000;
System.out.println("time" + elapsedTime);

Solution

You need to have a separate thread waiting for the method to terminate or time out Fortunately, the creators of the great guava library have achieved this: just use the timelimiter (in your case, simpletimelimiter)

Your code is as follows:

TimeLimiter limiter = new SimpleTimeLimiter();
String result = limiter.callWithTimeout(new Callable<String>() {
    public String call() {
      return getStaticJsonResponse("build","post");
    }
  },3,TimeUnit.SECONDS,false);

Suppose your method returns a string, otherwise adjust the return type

Note that, like other solutions, this ensures that callers can wait up to 3 time periods But it does not guarantee that the method execution will actually abort after 3 seconds Only when the called code is on thread Interrupt() is aborted only when it reacts to a thread interrupt All functions waiting for I / o do this, but your own code may not

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>