1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.commons.lang3.builder;
19
20 import java.util.ArrayList;
21 import java.util.Collection;
22 import java.util.LinkedList;
23 import java.util.List;
24 import java.util.concurrent.Callable;
25 import java.util.concurrent.CopyOnWriteArrayList;
26 import java.util.concurrent.ExecutorService;
27 import java.util.concurrent.Executors;
28 import java.util.concurrent.Future;
29 import java.util.concurrent.TimeUnit;
30
31 import org.apache.commons.lang3.AbstractLangTest;
32 import org.apache.commons.lang3.concurrent.UncheckedFuture;
33 import org.junit.jupiter.api.Test;
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48 class ToStringStyleConcurrencyTest extends AbstractLangTest {
49
50 static class CollectionHolder<T extends Collection<?>> {
51 T collection;
52
53 CollectionHolder(final T collection) {
54 this.collection = collection;
55 }
56 }
57
58 private static final List<Integer> LIST;
59 private static final int LIST_SIZE = 100000;
60 private static final int REPEAT = 100;
61
62 static {
63 LIST = new ArrayList<>(LIST_SIZE);
64 for (int i = 0; i < LIST_SIZE; i++) {
65 LIST.add(Integer.valueOf(i));
66 }
67 }
68
69 @Test
70 void testArrayList() throws InterruptedException {
71 testConcurrency(new CollectionHolder<>(new ArrayList<>()));
72 }
73
74 private void testConcurrency(final CollectionHolder<List<Integer>> holder) throws InterruptedException {
75 final List<Integer> list = holder.collection;
76
77 list.addAll(LIST);
78
79 final ExecutorService threadPool = Executors.newFixedThreadPool(2);
80 try {
81
82 final Callable<Integer> consumer = () -> {
83 for (int i = 0; i < REPEAT; i++) {
84
85 new ToStringBuilder(holder).append(holder.collection);
86 }
87 return Integer.valueOf(REPEAT);
88 };
89 final Collection<Callable<Integer>> tasks = new ArrayList<>();
90 tasks.add(consumer);
91 tasks.add(consumer);
92 final List<Future<Integer>> futures = threadPool.invokeAll(tasks);
93 UncheckedFuture.on(futures).forEach(UncheckedFuture::get);
94 } finally {
95 threadPool.shutdown();
96 threadPool.awaitTermination(1, TimeUnit.SECONDS);
97 }
98 }
99
100 @Test
101 void testCopyOnWriteArrayList() throws InterruptedException {
102 testConcurrency(new CollectionHolder<>(new CopyOnWriteArrayList<>()));
103 }
104
105 @Test
106 void testLinkedList() throws InterruptedException {
107 testConcurrency(new CollectionHolder<>(new LinkedList<>()));
108 }
109 }