Hi Guys and Gals,

Just a quick reminder about the following:

If you have a static field (or even a normal field) in a class or object that is being accessed by multiple threads, please make sure that you're either using the volatile keyword or a java.util.concurrent.atomic object such as AtomicInteger or AtomicReference.

The problem is that a change to a (static) field in one thread is not guaranteed to propagate to another thread unless you use the volatile keyword.

For example:

public class CupcakeManagement {

    private static int counter = 0;
   
    private final int id;
   
    public CupcakeManagement() {
       this.id = counter++;
    }
}


If multiple threads are creating instances of the CupcakeManagement class, then there's a possibility that two instances could be created with the same id field value. This happens because each thread keeps it's own copy of the "static int counter" field -- the JVM doesn't have to make sure different threads keep their value of a static field in sync unless volatile is used.

Thread A, B and C:

A: creates new instance of CupcakeManagement.
A: CupcakeManagement.counter == 0 and is incremented to 1 in thread A
A: CupcakeManagement instance this.id = 1
B: creates new instance of CupcakeManagement
B: counter == 0 in thread B and is incremented to 1 in thread B
B: CupcakeManagement instance this.id = 1

Simply using an AtomicInteger is also enough, because the java.util.concurrent.atomic classes use volatile in their objects to make sure that the above situation doesn't happen.

HTH!
Marco

-- 
jBPM/Drools developer
Utrecht, the Netherlands