1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 package org.hipparchus.analysis.integration.gauss;
23
24 import org.hipparchus.util.Pair;
25 import org.junit.jupiter.api.Test;
26
27 import java.util.ArrayList;
28 import java.util.List;
29 import java.util.concurrent.ArrayBlockingQueue;
30 import java.util.concurrent.Callable;
31 import java.util.concurrent.ExecutionException;
32 import java.util.concurrent.Future;
33 import java.util.concurrent.ThreadPoolExecutor;
34 import java.util.concurrent.TimeUnit;
35 import java.util.concurrent.atomic.AtomicInteger;
36
37 import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
38 import static org.junit.jupiter.api.Assertions.assertEquals;
39
40
41
42
43
44 class RuleFactoryTest {
45
46
47
48
49 @Test
50 void testConcurrentCreation() throws InterruptedException,
51 ExecutionException {
52
53 final int numTasks = 20;
54
55 final ThreadPoolExecutor exec
56 = new ThreadPoolExecutor(3, numTasks, 1, TimeUnit.SECONDS,
57 new ArrayBlockingQueue<Runnable>(2));
58
59 final List<Future<Pair<double[], double[]>>> results
60 = new ArrayList<Future<Pair<double[], double[]>>>();
61 for (int i = 0; i < numTasks; i++) {
62 results.add(exec.submit(new RuleBuilder()));
63 }
64
65
66 for (Future<Pair<double[], double[]>> f : results) {
67 f.get();
68 }
69
70
71 final int n = RuleBuilder.getNumberOfCalls();
72 assertEquals(1, n, "Rule computation was called " + n + " times");
73 }
74
75 private static class RuleBuilder implements Callable<Pair<double[], double[]>> {
76 private static final DummyRuleFactory factory = new DummyRuleFactory();
77
78 public Pair<double[], double[]> call() {
79 final int dummy = 2;
80 return factory.getRule(dummy);
81 }
82
83 public static int getNumberOfCalls() {
84 return factory.getNumberOfCalls();
85 }
86 }
87
88 private static class DummyRuleFactory extends AbstractRuleFactory {
89
90 private static AtomicInteger nCalls = new AtomicInteger();
91
92 @Override
93 protected Pair<double[], double[]> computeRule(int order) {
94
95 nCalls.getAndIncrement();
96
97 assertDoesNotThrow(() -> {
98
99 Thread.sleep(20);
100 }, "Unexpected interruption");
101
102
103 final double[] p = new double[order];
104 final double[] w = new double[order];
105 for (int i = 0; i < order; i++) {
106 p[i] = Double.valueOf(i);
107 w[i] = Double.valueOf(i);
108 }
109 return new Pair<>(p, w);
110 }
111
112 public int getNumberOfCalls() {
113 return nCalls.get();
114 }
115
116 }
117
118 }
119