Movatterモバイル変換


[0]ホーム

URL:


CodeQL documentation
CodeQL resources

Spin on field

ID: java/spin-on-fieldKind: problemSecurity severity: Severity: warningPrecision: mediumTags:   - quality   - reliability   - correctness   - concurrency   - performanceQuery suites:   - java-security-and-quality.qls

Click to see the query in the CodeQL repository

Repeatedly reading a non-volatile field within the condition of an empty loop statement may result in an infinite loop, since a compiler optimization may move this field access out of the loop.

Example

In the following example, the methodspin repeatedly tests the fielddone in a loop. The method repeats the while-loop until the value of the fielddone is set by another thread. However, the compiler could optimize the code as shown in the second code snippet, because the fielddone is not marked asvolatile and there are no statements in the body of the loop that could change the value ofdone. The optimized version ofspin loops forever, even when another thread would setdone totrue.

classSpin{publicbooleandone=false;publicvoidspin(){while(!done){}}}classSpin{// optimizedpublicbooleandone=false;publicvoidspin(){booleancond=done;while(!cond){}}}

Recommendation

Ensure that access to this field is properly synchronized. Alternatively, avoid spinning on the field and instead use thewait andnotifyAll methods or thejava.util.concurrent library to communicate between threads.

References


[8]ページ先頭

©2009-2025 Movatter.jp