ScopedProvider implements Provider<T> { @SuppressWarnings("unchecked") @Override public T get() { Object result = instance; if (result == UNINITIALIZED) { synchronized (this) { result = instance; if (result == UNINITIALIZED) { instance = result = factory.get(); } } } return (T) result; } private  ScopedProvider(Factory<T> factory); @SuppressWarnings("unchecked") // cast only happens when result comes from the factory @Override T get(); static Provider<T> create(Factory<T> factory);  }
@Test public void get() { Provider<Integer> scopedProvider = ScopedProvider.create(new Factory<Integer>() { int i = 0; @Override public Integer get() { return i++; } }); assert_().that(scopedProvider.get()).isEqualTo(0); assert_().that(scopedProvider.get()).isEqualTo(0); assert_().that(scopedProvider.get()).isEqualTo(0); }