Lazy field initialization with lambdas

后端 未结 14 2313
日久生厌
日久生厌 2020-11-29 23:39

I would like to implement lazy field initialization (or deferred initialization) without an if statement and taking advantage of lambdas. So, I would like to have the same b

14条回答
  •  伪装坚强ぢ
    2020-11-30 00:08

    You could do something along these lines :

       private Supplier heavy = () -> createAndCacheHeavy();
    
       public Heavy getHeavy()
       {
          return heavy.get();
       }
    
       private synchronized Heavy createAndCacheHeavy()
       {
          class HeavyFactory implements Supplier
          {
             private final Heavy heavyInstance = new Heavy();
    
             public Heavy get()
             {
                return heavyInstance;
             }
          }
    
          if(!HeavyFactory.class.isInstance(heavy))
          {
             heavy = new HeavyFactory();
          }
    
          return heavy.get();
       }
    

    I recently saw this as an idea by Venkat Subramaniam. I copied the code from this page.

    The basic idea is that the Supplier once called, replaces itself with a simpler factory implementation that returns the initialized instance.

    This was in the context of thread safe lazy initialization of a singleton, but you could also apply it to a normal field, obviously.

提交回复
热议问题