1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.eclipse.aether;
20
21 import java.util.UUID;
22 import java.util.concurrent.atomic.AtomicReference;
23 import java.util.function.Supplier;
24
25 import org.junit.Test;
26
27 import static org.junit.Assert.*;
28
29 public class DefaultSessionDataTest {
30
31 private DefaultSessionData data = new DefaultSessionData();
32
33 private Object get(Object key) {
34 return data.get(key);
35 }
36
37 private void set(Object key, Object value) {
38 data.set(key, value);
39 }
40
41 private boolean set(Object key, Object oldValue, Object newValue) {
42 return data.set(key, oldValue, newValue);
43 }
44
45 private Object computeIfAbsent(Object key, Supplier<Object> supplier) {
46 return data.computeIfAbsent(key, supplier);
47 }
48
49 @Test(expected = RuntimeException.class)
50 public void testGet_NullKey() {
51 get(null);
52 }
53
54 @Test(expected = RuntimeException.class)
55 public void testSet_NullKey() {
56 set(null, "data");
57 }
58
59 @Test
60 public void testGetSet() {
61 Object key = "key";
62 assertNull(get(key));
63 set(key, "value");
64 assertEquals("value", get(key));
65 set(key, "changed");
66 assertEquals("changed", get(key));
67 set(key, null);
68 assertNull(get(key));
69 }
70
71 @Test
72 public void testGetSafeSet() {
73 Object key = "key";
74 assertNull(get(key));
75 assertFalse(set(key, "wrong", "value"));
76 assertNull(get(key));
77 assertTrue(set(key, null, "value"));
78 assertEquals("value", get(key));
79 assertTrue(set(key, "value", "value"));
80 assertEquals("value", get(key));
81 assertFalse(set(key, "wrong", "changed"));
82 assertEquals("value", get(key));
83 assertTrue(set(key, "value", "changed"));
84 assertEquals("changed", get(key));
85 assertFalse(set(key, "wrong", null));
86 assertEquals("changed", get(key));
87 assertTrue(set(key, "changed", null));
88 assertNull(get(key));
89 assertTrue(set(key, null, null));
90 assertNull(get(key));
91 }
92
93 @Test
94 public void testComputeIfAbsent() {
95 Object key = "key";
96 assertNull(get(key));
97 assertEquals("value", computeIfAbsent(key, () -> "value"));
98 assertEquals("value", computeIfAbsent(key, () -> "changed"));
99 }
100
101 @Test(timeout = 10000L)
102 public void testConcurrency() throws Exception {
103 final AtomicReference<Throwable> error = new AtomicReference<>();
104 Thread[] threads = new Thread[20];
105 for (int i = 0; i < threads.length; i++) {
106 threads[i] = new Thread() {
107 @Override
108 public void run() {
109 for (int i = 0; i < 100; i++) {
110 String key = UUID.randomUUID().toString();
111 try {
112 set(key, Boolean.TRUE);
113 assertEquals(Boolean.TRUE, get(key));
114 } catch (Throwable t) {
115 error.compareAndSet(null, t);
116 t.printStackTrace();
117 }
118 }
119 }
120 };
121 }
122 for (Thread thread : threads) {
123 thread.start();
124 }
125 for (Thread thread : threads) {
126 thread.join();
127 }
128 assertNull(String.valueOf(error.get()), error.get());
129 }
130 }