singleton with volatile in java

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

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


        
9条回答
  •  耶瑟儿~
    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();
        }
    }
    

提交回复
热议问题