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