【问题标题】:to restrict the execution time of method in java限制java中方法的执行时间
【发布时间】:2018-01-25 13:15:12
【问题描述】:

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

但是我的代码没有抛出异常。

请帮助解决缺少的问题。

提前感谢您为相同目的提供的任何其他建议方法。

【问题讨论】:

  • 您是否按照您链接到的页面中的描述编织了您的课程?
  • 这样的注释不是单独工作的,而是在具体环境中工作的。阅读博客库,准确配置和使用方式
  • 对应的问题不好重复,但this answer可能还是有帮助的
  • 是@Jacek Cz,为了使所需的库可用,我添加了这个gradle依赖:编译组:'com.jcabi',名称:'jcabi-aspects',版本:'0.22'
  • @DawoodibnKareem 我在课堂上添加了与我链接到我的问题的页面上描述的相同的配置。您建议的其他一些更改??

标签: java


【解决方案1】:

对于您使用的方法,添加@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?

还要注意,如果超时或调用线程被中断,操作会显式取消,以避免浪费资源。

【讨论】:

    【解决方案2】:

    正如 cmets 中已经提到的,this solution 似乎也适用于您的情况。它看起来像这样:

    public void testMethod() {
        ForkJoinPool forkJoinPool = new ForkJoinPool(1);
        try {
            forkJoinPool.submit(() ->
            {
            // replace the following linea with the actual code that should be in this method
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {}
                System.out.println("Job done");
            })
            // wait for x milliseconds before wait times out and TimeOutException is thrown
                    .get(1000, TimeUnit.MILLISECONDS);
        } catch (TimeoutException e) {
            // job not done in your interval
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        } 
    }
    

    由于 Thread#sleep 需要 2 秒,超过了 .get(...) 中指定的 1 秒等待超时,因此在本示例中此方法将始终超时。

    【讨论】:

    • 谢谢!它按照您建议的代码-sn-p 的要求工作。
    【解决方案3】:

    这是代码及其自我解释:出于测试目的,我刚刚编写了一个简单的方法,它只执行 3 秒。

    import java.util.Timer;
    import java.util.TimerTask;
    
    class Test {
    
        Timer timer;
    
        public Test(int seconds) {
            timer = new Timer();
            timer.schedule(new RemindTask(), seconds * 1000);
        }
    
        class RemindTask extends TimerTask {
            public void run() {
                System.out.format("Time's up!%n");
                System.exit(0);
                timer.cancel();
            }
        }
    
        public static void main(String args[]) {
            Thread t = new Thread(new Runnable() {
                @Override
                public void run() {
                     new Test(3);
                     sum();
                     System.out.format("Task scheduled.%n");
                }
            });
           t.start();
        }
    
        public static void sum(){
            for(int i = 0 ; i < 100 ;i++){
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(i);
            }
        }
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-21
    • 2012-05-14
    • 2012-05-04
    相关资源
    最近更新 更多