title: singleton with volatile in java
body: <pre><code>class MyClass
  {
        private static volatile Resource resource;
  
        public static Resource getInstance()
        {
              if(resource == null)
                    resource = new Resource();
              return resource;
        }
   }
  </code></pre>
  
  <p>Here my doubt is according to java concurrency in practice if you use volatile, safe publication happens (i.e. as soon the reference is visible to another thread the data is also available). So can I use it here? But if it is correct then suppose thread1 now checks "resource" and it's null so it starts creating the object. While thread1 is creating the objet another thread i.e. thread2 comes and start checking the value of "resource" and thread2 finds it as null (assume creating "resource" object takes some considerable amount of time and as thread1 has not yet completed the creation so the safe publication hasn't happened hence unavailable to thread2 )then will it also start creating the object? if yes then class invariant breaks. Am I correct? Please help me in understanding this specially use of volatile here.</p>