JAVA.WAIT.IN.LOOP
Always invoke wait() and await() methods inside a loop
Vulnerability and risk
To ensure a wait() condition predicate is validated, the validation must take place after the response notification is received.
Mitigation and prevention
Ensure that wait() calls are made with a loop to ensure validation once the response notification is made.
Vulnerable code example 1
Copy
                                                            
                                                        
                                                    package com.klocwork;
public class JAVA_WAIT_IN_LOOP_POSITIVE_1 {
    public void test1(Object obj) throws InterruptedException {
        obj.wait();
    }
}Vulnerable code example 2
Copy
                                                        
                                                    
                                                package com.klocwork;
import java.util.concurrent.locks.Condition;
public class JAVA_WAIT_IN_LOOP_POSITIVE_2 {
    public void test1(Condition condition) throws InterruptedException {
        condition.await();
    }
}Fixed code example
Copy
                                                        
                                                    
                                                package com.klocwork;
import java.util.concurrent.locks.Condition;
public class JAVA_WAIT_IN_LOOP_NEGATIVE {
    public void test1(Object obj, Condition condition) throws InterruptedException {
        for (;;) {
            obj.wait();
            condition.await();
        }
    }
    public void test2(Object obj, Condition condition) throws InterruptedException {
        do {
            obj.wait();
            condition.await();
        } while (true);
    }
    
    public void test3(Object obj, Condition condition) throws InterruptedException {
        while (true) {
            obj.wait();
            condition.await();
        }
    }
}