View Javadoc
1   package com.github.mygreen.supercsv.util;
2   
3   import java.util.concurrent.atomic.AtomicBoolean;
4   import java.util.function.Supplier;
5   
6   /**
7    * 結果をキャッシュする {@link} Supplier} の実装クラス。
8    * <p>Google Guavaの {@code com.google.common.base.Suppliers.MemoizingSupplier} の実装を参考にしています。</p>
9    * 
10   * @param <T> キャッシュするオブジェクトの型
11   * @since 2.5
12   * @author T.TSUCHIE
13   *
14   */
15  public class MemorizingSupplier<T> implements Supplier<T> {
16      
17      private final Supplier<T> deleagte;
18  
19      private final AtomicBoolean initialized = new AtomicBoolean(false);
20  
21      private transient Object lock = new Object();
22      
23      private T value;
24      
25      public static <T> Supplier<T> of(final Supplier<T> deleagte) {
26          return new MemorizingSupplier<>(deleagte);
27      }
28      
29      /**
30       * デフォルトコンストラクタ
31       * @param deleagte キャッシュするオブジェクトを生成する {@link Supplier}
32       */
33      private MemorizingSupplier(final Supplier<T> deleagte) {
34          ArgUtils.notNull(deleagte, "deleagte");
35          this.deleagte = deleagte;
36      }
37      
38      @Override
39      public T get() {
40          
41          if (!initialized.get()) {
42              synchronized(lock) {
43                  this.value = deleagte.get();
44                  initialized.set(true);
45              }
46          }
47          
48          return value;
49      }
50      
51      /**
52       * このSupplierが初期化されているかどうかを返します。
53       * 
54       * @return 初期化されている場合はtrueを返します。
55       */
56      public boolean isInitialized() {
57          return initialized.get();
58      }
59  
60  }