gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-01 23:06:35 28 4
gpt4 key购买 nike

我在 NetBeans 中面临以下警告:

warning

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

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");
}

最佳答案

虽然 Thread.sleep() 很少是一个好的解决方案,但我认为您的情况是一个异常(exception),因为它使您的意图明确。所以,我会采纳@user1274820 的建议来添加一个@SuppressWarnings。但是,这是我在不使用 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
}
}

关于java - Thread.sleep 在循环中调用 - 在这种情况下如何防止它(通过重构)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38908433/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com