<html>
  <head>

    <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
  </head>
  <body bgcolor="#FFFFFF" text="#000000">
    Hi Guys and Gals, <br>
    <br>
    Just a quick reminder about the following: <br>
    <br>
    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 <b>volatile</b> keyword or a
    java.util.concurrent.atomic object such as AtomicInteger or
    AtomicReference. <br>
    <br>
    The problem is that a change to a (static) field in one thread is <u>not
      guaranteed to propagate</u> to another thread unless you use the
    volatile keyword. <br>
    <br>
    For example: <br>
    <br>
    <small><tt>public class CupcakeManagement {</tt><tt><br>
      </tt><tt><br>
      </tt><tt>&nbsp;&nbsp;&nbsp; private static int counter = 0;</tt><tt><br>
      </tt><tt>&nbsp;&nbsp;&nbsp; </tt><tt><br>
      </tt><tt>&nbsp;&nbsp;&nbsp; private final int id;</tt><tt><br>
      </tt><tt>&nbsp;&nbsp;&nbsp; </tt><tt><br>
      </tt><tt>&nbsp;&nbsp;&nbsp; public CupcakeManagement() { </tt><tt><br>
      </tt><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; this.id = counter++; </tt><tt><br>
      </tt><tt>&nbsp;&nbsp;&nbsp; }</tt><tt><br>
      </tt><tt>}</tt></small><br>
    <br>
    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 <i>unless volatile is used. <br>
      <br>
    </i>Thread A, B and C: <br>
    <br>
    A: creates new instance of CupcakeManagement. <br>
    A: CupcakeManagement.counter == 0 and is incremented to 1 <i>in
      thread A</i><br>
    A: CupcakeManagement instance this.id = 1<i><br>
    </i>B: creates new instance of CupcakeManagement<br>
    B: <i>counter == 0 in thread B and is incremented to 1 in thread B</i><br>
    B: CupcakeManagement instance this.id = 1<br>
    <br>
    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. <br>
    <br>
    HTH!<br>
    Marco<br>
    <br>
    <pre class="moz-signature" cols="72">-- 
jBPM/Drools developer
Utrecht, the Netherlands</pre>
  </body>
</html>