gpt4 book ai didi

java - 如何修复 Sonar 问题 "Remove this call to "等待“或将其移至 "while"循环”?

转载 作者:行者123 更新时间:2023-11-30 06:42:17 25 4
gpt4 key购买 nike

我收到一个修复遗留项目 Sonar 问题的请求,有这样一段代码,每次调用这个函数都会暂停 50ms:

synchronized(monitor) {

[...]

try {

[...]

Thread.sleep(config.getWaitTime()); // return 50
} catch (SomeException e) {
log.error(e.getMessage(), e);
}

[...]
}

首先,sonar 要求我将 Thread.sleep() 更改为 wait(),因此我将 try block 更改为:

try {

[..]

monitor.wait(config.getWaitTime());
} catch (SomeException e) {
log.error(e.getMessage(), e);
}

然后,出现另一个问题:删除对“等待”的调用或将其移入“while”循环,我对多线程没有太多经验,所以我不确定我的修复是正确的:

boolean wait = true;
while (wait) {
wait = false;
monitor.wait(config.getWaitTime());
}

上述解决方案是否正确?如果没有,我该怎么办?

最佳答案

来自Object#wait() Java doc

A thread can also wake up without being notified, interrupted, or timing out, a so-called spurious wakeup. While this will rarely occur in practice, applications must guard against it by testing for the condition that should have caused the thread to be awakened, and continuing to wait if the condition is not satisfied. In other words, waits should always occur in loops, like this one:

 synchronized (obj) {
while (<condition does not hold>)
obj.wait(timeout);
... // Perform action appropriate to condition
}

你的循环看起来不太好,它应该是这样的:

while (wait) {
monitor.wait(config.getWaitTime());
}

当不再需要等待条件时,必须从别处设置wait 变量。

关于java - 如何修复 Sonar 问题 "Remove this call to "等待“或将其移至 "while"循环”?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53738745/

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