java - 限制java中方法的执行时间

标签 java

我想限制 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/

相关文章:

java - querySkuDetailsAsync 正在返回带有 BillingResult 代码 SERVICE_UNAVAILABLE 的空列表

java - 致命异常 : java. lang.IllegalArgumentException fd 只能在 Android Q 中的 PrintAdapter 类的 onwrite() 中为 null

java - 如何从另一种方法打印数组中的特定点? #Java

java - Mac 上的 libGDX 项目在 IntelliJ android 中位置错误

Java:为什么我的 while 语句不适用于我的案例 2?

java - Hibernate 与多列一对一

java - 如何在 Play 中保存 ArrayList?

java - WebDriver.getWindowHandle() 方法

java - 当存在 2^n 条件时从递归函数返回的更好方法

java - 如何使 charAt() 返回一个可以填充数组的数字?