Java Coverity 锁语句上的无限期等待错误

标签 java coverity

对 Java 来说相对较新,但任务是检查 Coverity 缺陷。这件事真像我想的那么简单吗? (我无法说服代码所有者。)

 50       // this method is used when the program is run as a pojo.
 51        public static void main(final String[] args) {
 52
 53                startProgram();
 54
 55                // keep this here, for console app, needs to create a loop, but not for AS apps.
 56                lock = new Object();
 57

loop_outside_lock_insufficient: Because this loop occurs outside the locked region, it cannot be a sufficient check of the wait condition. The value of the wait condition may change between the check of the loop condition and the call to wait.
 58                while (!finished) {

lock_acquire: Acquiring lock program.lock.
 59                        synchronized (lock) {
 60                                try {

CID 711645 (#1 of 1): Indefinite wait (BAD_CHECK_OF_WAIT_COND)wait_cond_improperly_checked: The wait condition prompting the wait upon program.lock is not checked correctly. This code can wait for a condition that has already been satisfied, which can cause a never-ending wait.

Refactor the code to protect the call to wait with a loop that rechecks the wait condition inside the locked region.
 61                                        lock.wait();
 62                                } catch (final InterruptedException e) {
 63
 64                                        log.error(e.getStackTrace());
 65                                }
 66                        }
 67                }
 68
 69        }

我想我只是想将其更改为

synchronized(lock)
    while(!finished){
        try lock.wait();
        catch(InterruptedException e)
            log.error(e.getStackTrace());
        }

这有道理吗?我真的只需要将 while 循环移到 lock 语句内吗?

最佳答案

您需要将finished声明为 volatile 。那么你的解决方案就可以了。

关于Java Coverity 锁语句上的无限期等待错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35925226/

相关文章:

c++ - 我得到的掩护问题为 "Wrapper object use after free (WRAPPER_ESCAPE)"

java - 源代码更改时自动重新启动配置

c - MISRA 警告 12.4 : integer conversion resulted in truncation (negation operation)

c++ - C++ 是否自动将整数初始化为零?

java - 链表索引计数器

coverity - 如何在 Coverity Scan 中忽略/usr/include?

c - C 中的 FORWARD_NULL 与 UNINIT Coverity 错误

java - 通过在标记末尾添加 "/"来格式化 XMl 文档

java - 使用带有 JDBC ignite 的 Spring Boot Web 应用程序而不是连接 ignite 的 dot NET native 方法对性能有影响吗?

JavaFX软件设计