|
| 1 | +package net.datafaker.internal.helper; |
| 2 | + |
| 3 | +import org.junit.jupiter.api.Test; |
| 4 | + |
| 5 | +import java.util.concurrent.ExecutorService; |
| 6 | +import java.util.concurrent.atomic.AtomicInteger; |
| 7 | +import java.util.function.Supplier; |
| 8 | + |
| 9 | +import static java.util.concurrent.Executors.newFixedThreadPool; |
| 10 | +import static java.util.concurrent.TimeUnit.SECONDS; |
| 11 | +import static org.assertj.core.api.Assertions.assertThat; |
| 12 | + |
| 13 | +class LazyEvaluatedTest { |
| 14 | + private final AtomicInteger executions = new AtomicInteger(0); |
| 15 | + private final Supplier<Integer> slowLoader = () -> { |
| 16 | + sleep(); |
| 17 | + return executions.incrementAndGet(); |
| 18 | + }; |
| 19 | + |
| 20 | + private final LazyEvaluated<Integer> lazyEvaluated = new LazyEvaluated<>(slowLoader); |
| 21 | + |
| 22 | + @Test |
| 23 | + void notInitializedUntilCalled() { |
| 24 | + assertThat(executions.get()).isEqualTo(0); |
| 25 | + } |
| 26 | + |
| 27 | + @Test |
| 28 | + void initializedOnlyOnce() throws InterruptedException { |
| 29 | + int threadsCount = 5; |
| 30 | + ExecutorService threadPool = newFixedThreadPool(threadsCount); |
| 31 | + |
| 32 | + for (int i = 0; i < threadsCount; i++) { |
| 33 | + threadPool.submit(() -> { |
| 34 | + try { |
| 35 | + assertThat(lazyEvaluated.get()).isEqualTo(1); |
| 36 | + } catch (Throwable e) { |
| 37 | + System.out.printf("Loading failed...%s%n", e); |
| 38 | + } |
| 39 | + }); |
| 40 | + } |
| 41 | + |
| 42 | + threadPool.shutdown(); |
| 43 | + assertThat(threadPool.awaitTermination(10, SECONDS)).isTrue(); |
| 44 | + |
| 45 | + assertThat(executions.get()) |
| 46 | + .as("The slowLoader should be executed only once, even if the value was asked in multiple parallel threads.") |
| 47 | + .isEqualTo(1); |
| 48 | + } |
| 49 | + |
| 50 | + private static void sleep() { |
| 51 | + try { |
| 52 | + Thread.sleep(10); |
| 53 | + } catch (InterruptedException e) { |
| 54 | + throw new RuntimeException(e); |
| 55 | + } |
| 56 | + } |
| 57 | +} |
0 commit comments