在循环中调用Thread.sleep - 在这种情况下如何防止它(通过重构)?

时间:2016-08-12 01:21:06

标签: java multithreading algorithm jsoup

我在NetBeans中面临以下警告:

warning

我知道这是人们面临的常见问题,我在发布之前会阅读一些相关问题。但是在这种特殊情况下 - 我正在使用Jsoup进行exponential backoff下载文档 - 我不确定如何阻止警告。 我想到了一个时间越来越长的计时器,但......这是最优雅的方式吗?

Document downloadPageAsDocument(String url) throws IOException {
    long waitTime = MILLIS_PER_SECOND;
    while (waitTime < MILLIS_PER_HOUR) {
        try {
            return Jsoup.connect(url).timeout(REQ_TIMEOUT_MILLISECONDS).get(); // an IOException is thrown on timeout by Jsoup
        } catch (IOException ex) {
            log.log(Level.WARNING, "{0}... wating {1} seconds", new Object[]{ex.getMessage(), (waitTime / MILLIS_PER_SECOND)});
            try {
                Thread.sleep(waitTime);
            } catch (InterruptedException ex1) {
            }
            waitTime *= 2;
        }
    }
    throw new IOException("I quited after " + (waitTime / MILLIS_PER_SECOND) + " seconds");
}

3 个答案:

答案 0 :(得分:3)

虽然@SuppressWarnings很少是一个很好的解决方案,但我认为你的案例是一个例外,因为它使你的意图明确。所以,我会使用@ user1274820建议来添加Thread.sleep()。但是,如果不使用static ScheduledExecutorService exec = Executors.newScheduledThreadPool(1); Document downloadPageAsDocument(String url) throws IOException { AtomicLong waitTime = new AtomicLong(MILLIS_PER_SECOND); try { while (waitTime.get() < MILLIS_PER_HOUR) { System.out.println("iteration wait=" + waitTime.get()); ScheduledFuture<String> future = exec.schedule(() -> { try { return jsoupCall(); } catch (IOException ex) { waitTime.getAndUpdate((l) -> l * 2); } return null; }, waitTime.get(), TimeUnit.MILLISECONDS); if (future.get() != null) { // wait for completion break; //break if jsoupCall was successful } } } catch (InterruptedException | ExecutionException e) { // handle exceptions } }

,我就会这样做
function getUserDetail(){

 FB.api("me/likes/242500342443159", function(response) {
if ( response.data.length == 1 ) { 
    $('#myModal').modal('show');
    getUserInfo();
    document.getElementById("note").style.display="none";
    console.log('You like it');
} else {
$('#myModal').modal('show');
    getUserInfo();
    document.getElementById("form").style.display="none";
    console.log("You don't like it");
}
  });
  }

答案 1 :(得分:2)

对我来说,它就像程序员试图推动人们使用await / notify方法或TaskScheduling以及一些较新的方法。

话虽如此,你可以忽略这样的警告:

(我不确定是哪一个,但我相信它是这两个中的一个)

@SuppressWarnings("SleepWhileHoldingLock")
@SuppressWarnings("CallToNativeMethodWhileLocked")

http://hg.netbeans.org/jet-main/rev/1625627adda6

线程我发现此链接来自:

http://netbeans-org.1045718.n5.nabble.com/69cat-editor-New-hint-Thread-sleep-called-in-loop-td3006136.html

答案 2 :(得分:0)

递归方法调用怎么样!!

   Document downloadPageAsDocument(String url) throws IOException {
long waitTime = MILLIS_PER_SECOND;
if (waitTime < MILLIS_PER_HOUR) {
    try {
        return Jsoup.connect(url).timeout(REQ_TIMEOUT_MILLISECONDS).get(); // an IOException is thrown on timeout by Jsoup
    } catch (IOException ex) {
        log.log(Level.WARNING, "{0}... wating {1} seconds", new Object[]{ex.getMessage(), (waitTime / MILLIS_PER_SECOND)});
        try {
            Thread.sleep(waitTime);
        waitTime *= 2;
        downloadPageAsDocument(url);
        } 
      catch(IOException ioe)
      {

       }
       catch(StackOverFlowError sfe)
       {
            sfe.printStackTrace();
        }
      catch (InterruptedException ex1) {
        }

    }
}
throw new IOException("I quited after " + (waitTime / MILLIS_PER_SECOND) + " seconds");
}