DoubleCheckLazy implements Lazy<T> { @SuppressWarnings("unchecked") @Override public T get() { Object result = instance; if (result == UNINITIALIZED) { synchronized (this) { result = instance; if (result == UNINITIALIZED) { instance = result = provider.get(); } } } return (T) result; } private  DoubleCheckLazy(Provider<T> provider); @SuppressWarnings("unchecked") // cast only happens when result comes from the factory @Override T get(); static Lazy<T> create(Provider<T> provider);  }
@Test public void get() throws Exception { int numThreads = 10; ExecutorService executor = Executors.newFixedThreadPool(numThreads); final CountDownLatch latch = new CountDownLatch(numThreads); LatchedProvider provider = new LatchedProvider(latch); final Lazy<Object> lazy = DoubleCheckLazy.create(provider); List<Callable<Object>> tasks = Lists.newArrayListWithCapacity(numThreads); for (int i = 0; i < numThreads; i++) { tasks.add(new Callable<Object>() { @Override public Object call() throws Exception { latch.countDown(); return lazy.get(); } }); } List<Future<Object>> futures = executor.invokeAll(tasks); assert_().that(provider.provisions.get()).isEqualTo(1); Set<Object> results = Sets.newIdentityHashSet(); for (Future<Object> future : futures) { results.add(future.get()); } assert_().that(results.size()).isEqualTo(1); }