1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.lang3.concurrent;
18
19 import static org.junit.jupiter.api.Assertions.assertEquals;
20 import static org.junit.jupiter.api.Assertions.assertNull;
21
22 import java.util.concurrent.atomic.AtomicBoolean;
23 import java.util.concurrent.atomic.AtomicInteger;
24
25 import org.apache.commons.lang3.function.FailableConsumer;
26 import org.apache.commons.lang3.function.FailableSupplier;
27 import org.junit.jupiter.api.BeforeEach;
28 import org.junit.jupiter.api.Test;
29
30
31
32
33 public class AtomicSafeInitializerSupplierTest extends AbstractConcurrentInitializerCloseAndExceptionsTest {
34
35
36 private AtomicInteger initCounter = new AtomicInteger();
37
38
39
40
41
42
43 @Override
44 protected ConcurrentInitializer<Object> createInitializer() {
45 return AtomicSafeInitializer.<Object>builder().setInitializer(this::incAndMakeObject).get();
46 }
47
48 @Override
49 protected ConcurrentInitializer<CloseableObject> createInitializerThatThrowsException(
50 final FailableSupplier<CloseableObject, ? extends Exception> supplier,
51 final FailableConsumer<CloseableObject, ? extends Exception> closer) {
52 return AtomicSafeInitializer.<CloseableObject>builder().setInitializer(supplier).setCloser(closer).get();
53 }
54
55
56 private Object incAndMakeObject() {
57 initCounter.incrementAndGet();
58 return new Object();
59 }
60
61 @BeforeEach
62 public void setUp() {
63 initCounter = new AtomicInteger();
64 }
65
66 @Test
67 public void testGetThatReturnsNullFirstTime() throws ConcurrentException {
68 final AtomicSafeInitializer<Object> initializer = new AtomicSafeInitializer<Object>() {
69 final AtomicBoolean firstRun = new AtomicBoolean(true);
70
71 @Override
72 protected Object initialize() {
73 if (firstRun.getAndSet(false)) {
74 return null;
75 } else {
76 return new Object();
77 }
78 }
79 };
80
81 assertNull(initializer.get());
82 assertNull(initializer.get());
83 }
84
85
86
87
88
89
90
91 @Test
92 public void testNumberOfInitializeInvocations() throws ConcurrentException, InterruptedException {
93 testGetConcurrent();
94 assertEquals(1, initCounter.get(), "Wrong number of invocations");
95 }
96 }