singleton with volatile in java

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

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


        
9条回答
  •  青春惊慌失措
    2020-12-31 06:48

    volatile solves one issue that is visibility issue . If you are writing to one variable that is declared volatile then the value will be visible to other thread immediately. As we all know we have different level of cache in os L1, L2, L3 and if we write to a variable in one thread it is not guaranteed to be visible to other, so if we use volatile it writes to direct memory and is visible to others. But volatile does not solve the issue of atomicity i.e. int a; a++; is not safe. AS there are three machine instructions associated to it.

提交回复
热议问题