Volatile Variable Inspections

April 24, 2007

Modern IDEs (IDEA, Eclipse) provide developers with lots of assistance when writing code. These IDEs mark code that is:

  • just plain wrong (won’t compile)
  • not used
  • can be simplified
  • and lots more

Can modern IDEs help developers find threading bugs? Let’s take a look at a specific example and find out.

public class Example {

    private boolean running = true;

    /**
     * Thread A starts counting
     */
    public void startCounting() {

        // Thread A keeps going until Thread B calls stop. Thread A may never stop!
        while (running) {
            countSomeSheep();
        }
    }

    /**
     * Thread B calls stop.
     */
    public void stop() {
        this.running = false;
    }

    /**
     * Executed by thread A.
     */
    private void countSomeSheep() {
        // zzz zzz zzz
    }
}

So what is wrong with the code? For a great explanation please review 3.1.4 Volatile variables in “Java Concurrency In Practice” book.

After reading that section you understand why the boolean variable named running should be marked volatile.

Let’s turn our attention to my favorite IDE for help tracking down this threading problem. IDEA (version 7, code named Selena) has an inspection named “While loop spins on field”. Here is the inspection’s description:

This inspection reports on any instances of while loops which spin on the value of a non-volatile field, waiting for it to be changed by another thread. In addition to being potentially extremely CPU intensive when little work is done inside the loop, such loops are likely have different semantics than intended, as the Java Memory Model allows such field accesses to be hoisted out of the loop, causing the loop to never complete even if another thread does change the field’s value.

Here is a snapshot of IDEA highlighting the threading problem:
Non-Volatile IDEA Inspection

Here is a snapshot of IDEA after making running volatile:

NOTE: IDEA 6.0.5 also has this inspection but it did not work!
NOTE: I have no idea if Eclipse has a similiar inspection.

Enjoy!