singleton with volatile in java

前端 未结 9 1005
暖寄归人
暖寄归人 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.

    0 讨论(0)
  • 2020-12-31 06:49

    I know you aren't asking about better solutions but this is definitely worth if you are looking for a lazy singleton solution.

    Use a private static class to load the singleton. The class isn't loaded until invocation and so the reference isn't loaded until the class is. Class loading by implementation is thread-safe and you also incur very little overhead (in case you are doing repetitive volatile loads [which may still be cheap], this resolution always normal loads after initial construction).

    class MyClass {
        public static Resource getInstance() {
            return ResourceLoader.RESOURCE;
        }
    
        private static final class ResourceLoader {
            private static final Resource RESOURCE = new Resource();
        }
    }
    
    0 讨论(0)
  • 2020-12-31 06:50

    I think, you should use syncronized keyword before getInstance definition.

    For better performance you can use Double-checked locking pattern:

    • Double-checked locking and the Singleton pattern on IBM
    • Double-checked locking on Wiki
    0 讨论(0)
提交回复
热议问题