我想限制 java 中一个方法的执行时间,我想要我的特定方法,如果它在某个特定的定义时间执行,那么就可以,否则它应该抛出异常。
为此我尝试使用 as :
@Timeable(limit = 1000, unit = TimeUnit.MILLISECONDS)
public void testMethod(){
try {
Thread.sleep(2000);
if (Thread.interrupted()) {
throw new InterruptedException();
}
}catch(InterruptedException e1){
logger.error("failed due to-" + e1, e1.getMessage());
throw new InterruptedException(e1.getMessage());
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new Exception(e.getMessage());
}
}
为此,我引用了: http://www.yegor256.com/2014/06/20/limit-method-execution-time.html
它应该在行之后抛出异常:
Thread.sleep(2000);
但是我的代码没有抛出异常。
请帮助缺少什么。
提前感谢出于相同目的的任何其他建议方法。
最佳答案
对于您使用的方法,仅添加 @Timeable
注释是不够的,您还需要按照 Weaving Java Binaries 中的说明配置切面编织。 .
有趣的是,jcabi-aspects 的博文作者和创建者| , Yegor Bugayenko, 已经决定Java annotations are a big mistake .
另一种方法是使用CompletableFuture
:
public void testMethod() {
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException("Interrupted", e);
}
});
try {
future.get(1000, TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
// Operation timed out. Cancel it and log.
future.cancel(true);
logger.error("Timed out", e);
} catch (InterruptedException e) {
// Current thread interrupted while waiting. Cancel operation and log.
future.cancel(true);
logger.error("Interrupted", e);
// Reassert interrupt flag, since exception is not propagated.
Thread.currentThread().interrupt();
} catch (ExecutionException e) {
logger.error("Operation failed", e.getCause());
// No need to cancel in this case, since the operation has completed.
}
}
请注意,代码总是在捕获 InterruptedException
时重新声明中断状态。参见 Why invoke Thread.currentThread.interrupt() in a catch InterruptException block?
另请注意,如果超时或调用线程被中断,操作将被显式取消,以避免浪费资源。
关于java - 限制java中方法的执行时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45729746/