| 73 | } |
| 74 | |
| 75 | @Test |
| 76 | public void get() throws Exception { |
| 77 | int numThreads = 10; |
| 78 | ExecutorService executor = Executors.newFixedThreadPool(numThreads); |
| 79 | |
| 80 | final CountDownLatch latch = new CountDownLatch(numThreads); |
| 81 | LatchedProvider provider = new LatchedProvider(latch); |
| 82 | final Lazy<Object> lazy = DoubleCheck.lazy(provider); |
| 83 | |
| 84 | List<Callable<Object>> tasks = Lists.newArrayListWithCapacity(numThreads); |
| 85 | for (int i = 0; i < numThreads; i++) { |
| 86 | tasks.add( |
| 87 | () -> { |
| 88 | latch.countDown(); |
| 89 | return lazy.get(); |
| 90 | }); |
| 91 | } |
| 92 | |
| 93 | List<Future<Object>> futures = executor.invokeAll(tasks); |
| 94 | |
| 95 | assertThat(provider.provisions.get()).isEqualTo(1); |
| 96 | Set<Object> results = Sets.newIdentityHashSet(); |
| 97 | for (Future<Object> future : futures) { |
| 98 | results.add(future.get()); |
| 99 | } |
| 100 | assertThat(results).hasSize(1); |
| 101 | } |
| 102 | |
| 103 | private static class LatchedProvider implements Provider<Object> { |
| 104 | final AtomicInteger provisions; |