singleton with volatile in java

前端 未结 9 1113
暖寄归人
暖寄归人 2020-12-31 06:23
class MyClass
{
      private static volatile Resource resource;

      public static Resource getInstance()
      {
            if(resource == null)
                        


        
9条回答
  •  余生分开走
    2020-12-31 06:27

    You are correct, multiple threads could try to create a Resource object. Volatile just guarantees that if one thread updates the reference, all other threads will see the new reference, not some cached reference. This is slower, but safer.

    If you require only a single resource that is lazy loaded, you need to do something like this:

    class MyClass
    {
          private static volatile Resource resource;
          private static final Object LOCK = new Object();
    
          public static Resource getInstance()
          {
                if(resource == null) { 
                    synchronized(LOCK) { // Add a synch block
                        if(resource == null) { // verify some other synch block didn't
                                               // write a resource yet...
                            resource = new Resource();
                        }
                    }
                }
                return resource;
          }
     }
    

提交回复
热议问题