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
49 public class ToStringStyleConcurrencyTest extends AbstractLangTest {
50
51 static class CollectionHolder<T extends Collection<?>> {
52 T collection;
53
54 CollectionHolder(final T collection) {
55 this.collection = collection;
56 }
57 }
58
59 private static final List<Integer> LIST;
60 private static final int LIST_SIZE = 100000;
61 private static final int REPEAT = 100;
62
63 static {
64 LIST = new ArrayList<>(LIST_SIZE);
65 for (int i = 0; i < LIST_SIZE; i++) {
66 LIST.add(Integer.valueOf(i));
67 }
68 }
69
70 @Test
71 public void testArrayList() throws InterruptedException {
72 this.testConcurrency(new CollectionHolder<>(new ArrayList<>()));
73 }
74
75 private void testConcurrency(final CollectionHolder<List<Integer>> holder) throws InterruptedException {
76 final List<Integer> list = holder.collection;
77
78 list.addAll(LIST);
79
80 final ExecutorService threadPool = Executors.newFixedThreadPool(2);
81 try {
82
83 final Callable<Integer> consumer = () -> {
84 for (int i = 0; i < REPEAT; i++) {
85
86 new ToStringBuilder(holder).append(holder.collection);
87 }
88 return Integer.valueOf(REPEAT);
89 };
90 final Collection<Callable<Integer>> tasks = new ArrayList<>();
91 tasks.add(consumer);
92 tasks.add(consumer);
93 final List<Future<Integer>> futures = threadPool.invokeAll(tasks);
94 UncheckedFuture.on(futures).forEach(UncheckedFuture::get);
95 } finally {
96 threadPool.shutdown();
97 threadPool.awaitTermination(1, TimeUnit.SECONDS);
98 }
99 }
100
101 @Test
102 public void testCopyOnWriteArrayList() throws InterruptedException {
103 this.testConcurrency(new CollectionHolder<>(new CopyOnWriteArrayList<>()));
104 }
105
106 @Test
107 public void testLinkedList() throws InterruptedException {
108 this.testConcurrency(new CollectionHolder<>(new LinkedList<>()));
109 }
110 }