title: Why is it necessary to copy the volatile variable instead of using it directly?
body: <p>In the book <a href="http://jcip.net/" rel="nofollow">Java concurrency in practice</a>, there is an example of customized thread (See Listing 8.7 in section 8.3.4). I pasted the code below. There is one thing I don't quite understand. That is, the <code>run()</code> method copies the volatile variable <code>debugLifecycle</code> before using it. And it has a comment <em>Copy debug flag to ensure consistent value throughout</em>. Is there any need to copy the variable here? If yes, why?</p>
  
  <pre class="lang-java prettyprint-override"><code>public class MyAppThread extends Thread {
      public static final String DEFAULT_NAME = "MyAppThread";
      private static volatile boolean debugLifecycle = false;
  
      public MyAppThread(Runnable r) {
          this(r, DEFAULT_NAME);
      }
  
      public MyAppThread(Runnable runnable, String name) {
          super(runnable, name + "-" + created.incrementAndGet());
          setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
              public void uncaughtException(Thread t,
                                            Throwable e) {
                  log.log(Level.SEVERE,
                          "UNCAUGHT in thread " + t.getName(), e);
              }
          });
      }
  
      public void run() {
          // Question: why copy the volatile variable here?
          // Copy debug flag to ensure consistent value throughout.
          boolean debug = debugLifecycle;
          if (debug) log.log(Level.FINE, "Created " + getName());
          try {
              alive.incrementAndGet();
              super.run();
          } finally {
              alive.decrementAndGet();
              if (debug) log.log(Level.FINE, "Exiting " + getName());
          }
      }
  }
  </code></pre>