title: Volatile class instances and member access in Java
body: <p>I think what I'm doing is correct, but since this could blow up quite badly if not, I'd really like clarification.</p>
  
  <p>The code is an example to try and express the point, sorry for any minor typos.</p>
  
  <p>I have the following class </p>
  
  <pre><code>public class Components
  {
      public final String mVar1;
      public final boolean mVar2;
  
      public Components(String var1, boolean var2)
      {
          mVar1 = mVar1;
          mVar2 = mVar2;
      }
  }
  </code></pre>
  
  <p>If I create a volatile instance of this class, I believe that assigning the value of this component to the address of one already created and in memory is thread safe.</p>
  
  <pre><code>public class Storage
  {
      public static volatile Components sComponents = null;
  }
  </code></pre>
  
  <p>So, regardless of whether I set this variable on the main or any other thread (where a set will simply point it to an object already created, NOT create a new one), it should be thread safe, because the volatile keyword is acting on the Components reference, which will just be updated to point to the object that already exists.</p>
  
  <p>So, for example</p>
  
  <pre><code>public class ThreadedClass
  {
      public ThreadedClass()
      {
          // Create an instance of Components so we have something to copy
          mInitialComponents = new Components("My String", false);
  
          // Spin off a thread
          create_a_new_thread( threadEntryPoint );
      }
  
      // This function is called every frame on the main thread
      public void update()
      {
          // If we have our components, print them out
          if (Storage.sComponents != null)
          {
              print(sComponents.mVar1);
              print(sComponents.mVar2);
          }
      }
  
      private Components mInitialComponents = null;
  
      private void threadEntryPoint()
      {
          // Just sleep for a bit so update gets called a few times
          sleep(3000);
  
          // Set our components
          Storage.sComponents = mInitialComponents;
      }
  }
  </code></pre>
  
  <p>(In the real world code, mInitialComponents is created and accessed via a synchronized function so accessing the original object is thread safe).</p>
  
  <p>So, my question is, when calling update on the main or any other thread, once Storage.sComponents has been set to the existing object in threadEntryPoint, is it simply updating the objects reference, so the object will be guaranteed to be complete whenever we check for null.</p>
  
  <p>Or is it possible for some or none of the internal members to have been correctly assigned.</p>
  
  <p>Thanks</p>