public static < T > Supplier < T > memoizeLock ( Supplier < T > delegate ) { AtomicReference < T > value = new AtomicReference <> ( ) ; return ( ) -> { // A 2-field variant of Double Checked Locking. T val = value . get ( ) ; if ( val == null ) { synchronized ( value ) { val = value . get ( ) ; if ( val == null ) { val = Objects . requireNonNull ( delegate . get ( ) ) ; value . set ( val ) ; } } } return val ; } ; }
Stolen from Googles Guava Suppliers . java