GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • CodeQL documentation
  • CodeQL overview
  • Writing CodeQL queries
  • CodeQL language guides
  • QL language reference
  • CodeQL standard-libraries
  • CodeQL query help
  • CodeQL repository
  • QL publications
  • CodeQL query help for C and C++
  • CodeQL query help for C#
  • CodeQL query help for GitHub Actions
  • CodeQL query help for Go
  • CodeQL query help for Java and Kotlin

This view

  • Original page
  • New address

GeezerVison is showing codeql.github.com — Spin on field — CodeQL query help documentation

Spin on field¶

ID: java/spin-on-field
Kind: problem
Security severity: 
Severity: warning
Precision: medium
Tags:
   - quality
   - reliability
   - correctness
   - concurrency
   - performance
Query 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 method spin repeatedly tests the field done in a loop. The method repeats the while-loop until the value of the field done is set by another thread. However, the compiler could optimize the code as shown in the second code snippet, because the field done is not marked as volatile and there are no statements in the body of the loop that could change the value of done. The optimized version of spin loops forever, even when another thread would set done to true.

class Spin {
    public boolean done = false;

    public void spin() {
        while(!done){
        }
    }
}

class Spin { // optimized
    public boolean done = false;

    public void spin() {
        boolean cond = done;
        while(!cond){
        }
    }
}

Recommendation¶

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

References¶

  • Java Language Specification: Threads and Locks.

  • © GitHub, Inc.
  • Terms
  • Privacy
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.