singleton with volatile in java

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

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


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

    volatile keyword guarantees that read and write to that variable are atomic.

    According to the tutorial

    Reads and writes are atomic for all variables declared volatile
    

    Using volatile variables reduces the risk of memory consistency errors, because any write to a volatile variable establishes a happens-before relationship with subsequent reads of that same variable. This means that changes to a volatile variable are always visible to other threads. What's more, it also means that when a thread reads a volatile variable, it sees not just the latest change to the volatile, but also the side effects of the code that led up the change.

提交回复
热议问题