1
|
package eu.dnetlib.miscutils.functional;
|
2
|
|
3
|
import static org.junit.Assert.*;
|
4
|
|
5
|
import java.util.concurrent.ExecutorService;
|
6
|
import java.util.concurrent.Executors;
|
7
|
|
8
|
import org.junit.Before;
|
9
|
import org.junit.Test;
|
10
|
|
11
|
import eu.dnetlib.miscutils.functional.ThreadSafeUnaryFunction;
|
12
|
import eu.dnetlib.miscutils.functional.UnaryFunction;
|
13
|
|
14
|
public class ThreadSafeUnaryFunctionTest {
|
15
|
|
16
|
/**
|
17
|
* Object under test.
|
18
|
*/
|
19
|
private ThreadSafeUnaryFunction<String, Integer> tsUnaryFunction;
|
20
|
|
21
|
private final static int N_THREAD = 10;
|
22
|
|
23
|
private ExecutorService executor;
|
24
|
|
25
|
@Before
|
26
|
public void setUp() {
|
27
|
executor = Executors.newFixedThreadPool(N_THREAD);
|
28
|
}
|
29
|
|
30
|
/**
|
31
|
* method creates N_THREAD threads such that each one performs a function.evaluate call
|
32
|
* @param function
|
33
|
*/
|
34
|
private void createThreads(final ThreadSafeUnaryFunction<String, Integer> function) {
|
35
|
for (int i = 0; i < N_THREAD; i++) {
|
36
|
final Integer j = i;
|
37
|
executor.execute(new Runnable() {
|
38
|
|
39
|
@Override
|
40
|
public void run() {
|
41
|
assertEquals(String.valueOf(j), function.evaluate(j));
|
42
|
}
|
43
|
});
|
44
|
}
|
45
|
}
|
46
|
|
47
|
@Test
|
48
|
public void testThreadSafeUnaryFunction_1() {
|
49
|
tsUnaryFunction = new ThreadSafeUnaryFunction<String, Integer>(new ThreadLocal<UnaryFunction<String, Integer>>() {
|
50
|
@Override
|
51
|
protected synchronized UnaryFunction<String, Integer> initialValue() {
|
52
|
return new UnsafeUnaryFunction();
|
53
|
}
|
54
|
});
|
55
|
createThreads(tsUnaryFunction);
|
56
|
}
|
57
|
|
58
|
}
|