1 |
dl |
1.1 |
/* |
2 |
|
|
* Written by Doug Lea with assistance from members of JCP JSR-166 |
3 |
|
|
* Expert Group and released to the public domain, as explained at |
4 |
|
|
* http://creativecommons.org/publicdomain/zero/1.0/ |
5 |
|
|
*/ |
6 |
|
|
|
7 |
|
|
import java.util.concurrent.*; |
8 |
|
|
import java.util.concurrent.atomic.*; |
9 |
|
|
|
10 |
|
|
/* |
11 |
|
|
* A simple test for evaluating different implementations of |
12 |
|
|
* CopyOnWriteArrayList.addIfAbsent. |
13 |
|
|
*/ |
14 |
|
|
|
15 |
|
|
public class COWALAddIfAbsentLoops { |
16 |
|
|
|
17 |
|
|
static final int SIZE = 25000; |
18 |
|
|
|
19 |
|
|
public static void main(String[] args) throws Exception { |
20 |
|
|
for (int reps = 0; reps < 4; ++reps) { |
21 |
|
|
for (int i = 1; i <= 4; ++i) |
22 |
|
|
test(i); |
23 |
|
|
} |
24 |
|
|
} |
25 |
|
|
|
26 |
|
|
static AtomicInteger result = new AtomicInteger(); |
27 |
|
|
|
28 |
|
|
public static void test(int n) throws Exception { |
29 |
|
|
result.set(0); |
30 |
|
|
Phaser started = new Phaser(n + 1); |
31 |
|
|
CopyOnWriteArrayList<Integer> list = new CopyOnWriteArrayList<Integer>(); |
32 |
|
|
Thread[] ts = new Thread[n]; |
33 |
|
|
for (int i = 0; i < n; ++i) |
34 |
|
|
(ts[i] = new Thread(new Task(i, n, list, started))).start(); |
35 |
|
|
long p = started.arriveAndAwaitAdvance(); |
36 |
|
|
long st = System.nanoTime(); |
37 |
|
|
for (int i = 0; i < n; ++i) |
38 |
|
|
ts[i].join(); |
39 |
|
|
double secs = ((double)System.nanoTime() - st) / (1000L * 1000 * 1000); |
40 |
|
|
System.out.println("Threads: " + n + " Time: " + secs); |
41 |
|
|
if (result.get() != SIZE) |
42 |
|
|
throw new Error(); |
43 |
|
|
} |
44 |
|
|
|
45 |
|
|
static final class Task implements Runnable { |
46 |
|
|
final int id, stride; |
47 |
|
|
final CopyOnWriteArrayList<Integer> list; |
48 |
|
|
final Phaser started; |
49 |
|
|
Task(int id, int stride, |
50 |
|
|
CopyOnWriteArrayList<Integer> list, Phaser started) { |
51 |
|
|
this.id = id; |
52 |
|
|
this.stride = stride; |
53 |
|
|
this.list = list; |
54 |
|
|
this.started = started; |
55 |
|
|
} |
56 |
|
|
public void run() { |
57 |
|
|
final CopyOnWriteArrayList<Integer> list = this.list; |
58 |
|
|
int origin = id, inc = stride, adds = 0; |
59 |
|
|
started.arriveAndAwaitAdvance(); |
60 |
|
|
for (int i = origin; i < SIZE; i += inc) { |
61 |
|
|
if (list.addIfAbsent(i)) |
62 |
|
|
++adds; |
63 |
|
|
} |
64 |
|
|
result.getAndAdd(adds); |
65 |
|
|
} |
66 |
|
|
} |
67 |
|
|
} |