【问题标题】:Adding timeouts for a method executing multiple paths为执行多条路径的方法添加超时
【发布时间】:2016-12-19 15:31:34
【问题描述】:

我有以下方法定义

   private void pollForStatus() throws  InterruptedException {

            if (state.equals("running")) {
                log.debug("Task still running, Polling again ..");
                TimeUnit.SECONDS.sleep(1);
                pollForStatus();
            }

            else if (state.equals("complete") ) {
                return;
            }

            else if (state.equals("stopped")) {
            {
                    // Report error state

            }

}

现在为了使这个“pllForStatus”在某些情况下不会继续执行,我想为递归添加一个超时。这在Java(7)中是如何实现的?

【问题讨论】:

  • 递归不应该适用于基本情况吗?
  • 基本情况是如果上述情况下的“状态”改变正确吗?我更多地考虑是否由于某种原因状态卡在“运行”状态导致递归无限期递归
  • 一种方法是 b 使用 System.currentTimeMillis 记录线程开始的时间,然后计算未来时间,并在每个循环中确保未来时间尚未过去。有这样的效果
  • 我应该在递归调用之前比较时间吗?
  • 是的。我用代码 sn-p 更新我的答案

标签: java recursion timeout


【解决方案1】:
long futureTime = System.currentTimeMillis + yourInterval;
private void pollForStatus() throws InterruptedException {

    if (state.equals("running")) {
        log.debug("Task still running, Polling again ..");
        TimeUnit.SECONDS.sleep(1);

        //havnt reached cut off time yet, loop again
        if(System.currentTimeMilis() < futureTime){
            pollForStatus();
        }
    } else if (state.equals("complete")) {
        return;
    } else if (state.equals("stopped")) {

        // Report error state

    }


}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-10
    • 2022-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-22
    相关资源
    最近更新 更多