Home | History | Annotate | Download | only in internal
      1 /*
      2  * Copyright (C) 2014 Google, Inc.
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  * http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 package dagger.internal;
     17 
     18 import dagger.Lazy;
     19 import javax.inject.Provider;
     20 
     21 /**
     22  * A {@link Provider} implementation that memoizes the result of a {@link Factory} instance.
     23  *
     24  * @author Gregory Kick
     25  * @since 2.0
     26  */
     27 public final class ScopedProvider<T> implements Provider<T>, Lazy<T> {
     28   private static final Object UNINITIALIZED = new Object();
     29 
     30   private final Factory<T> factory;
     31   private volatile Object instance = UNINITIALIZED;
     32 
     33   private ScopedProvider(Factory<T> factory) {
     34     assert factory != null;
     35     this.factory = factory;
     36   }
     37 
     38   @SuppressWarnings("unchecked") // cast only happens when result comes from the factory
     39   @Override
     40   public T get() {
     41     // double-check idiom from EJ2: Item 71
     42     Object result = instance;
     43     if (result == UNINITIALIZED) {
     44       synchronized (this) {
     45         result = instance;
     46         if (result == UNINITIALIZED) {
     47           instance = result = factory.get();
     48         }
     49       }
     50     }
     51     return (T) result;
     52   }
     53 
     54   /** Returns a new scoped provider for the given factory. */
     55   public static <T> Provider<T> create(Factory<T> factory) {
     56     if (factory == null) {
     57       throw new NullPointerException();
     58     }
     59     return new ScopedProvider<T>(factory);
     60   }
     61 }
     62