7 |
|
import java.util.concurrent.Executors; |
8 |
|
import java.util.concurrent.ExecutorService; |
9 |
|
import java.util.concurrent.Phaser; |
10 |
+ |
import java.util.concurrent.ThreadLocalRandom; |
11 |
|
import java.util.concurrent.atomic.LongAccumulator; |
12 |
|
|
13 |
|
import junit.framework.Test; |
119 |
|
* accumulates by multiple threads produce correct result |
120 |
|
*/ |
121 |
|
public void testAccumulateAndGetMT() { |
122 |
< |
final int incs = 1000000; |
123 |
< |
final int nthreads = 4; |
124 |
< |
final ExecutorService pool = Executors.newCachedThreadPool(); |
125 |
< |
LongAccumulator a = new LongAccumulator(Long::max, 0L); |
126 |
< |
Phaser phaser = new Phaser(nthreads + 1); |
127 |
< |
for (int i = 0; i < nthreads; ++i) |
128 |
< |
pool.execute(new AccTask(a, phaser, incs)); |
128 |
< |
phaser.arriveAndAwaitAdvance(); |
129 |
< |
phaser.arriveAndAwaitAdvance(); |
130 |
< |
long expected = incs - 1; |
131 |
< |
long result = a.get(); |
132 |
< |
assertEquals(expected, result); |
133 |
< |
pool.shutdown(); |
134 |
< |
} |
135 |
< |
|
136 |
< |
static final class AccTask implements Runnable { |
137 |
< |
final LongAccumulator acc; |
138 |
< |
final Phaser phaser; |
139 |
< |
final int incs; |
140 |
< |
volatile long result; |
141 |
< |
AccTask(LongAccumulator acc, Phaser phaser, int incs) { |
142 |
< |
this.acc = acc; |
143 |
< |
this.phaser = phaser; |
144 |
< |
this.incs = incs; |
145 |
< |
} |
146 |
< |
|
147 |
< |
public void run() { |
122 |
> |
final LongAccumulator acc |
123 |
> |
= new LongAccumulator((x, y) -> x + y, 0L); |
124 |
> |
final int nThreads = ThreadLocalRandom.current().nextInt(1, 5); |
125 |
> |
final Phaser phaser = new Phaser(nThreads + 1); |
126 |
> |
final int incs = 1_000_000; |
127 |
> |
final long total = nThreads * incs/2L * (incs - 1); // Gauss |
128 |
> |
final Runnable task = () -> { |
129 |
|
phaser.arriveAndAwaitAdvance(); |
130 |
< |
LongAccumulator a = acc; |
131 |
< |
for (int i = 0; i < incs; ++i) |
132 |
< |
a.accumulate(i); |
133 |
< |
result = a.get(); |
130 |
> |
for (int i = 0; i < incs; i++) { |
131 |
> |
acc.accumulate((long) i); |
132 |
> |
assertTrue(acc.get() <= total); |
133 |
> |
} |
134 |
|
phaser.arrive(); |
135 |
+ |
}; |
136 |
+ |
final ExecutorService p = Executors.newCachedThreadPool(); |
137 |
+ |
try (PoolCleaner cleaner = cleaner(p)) { |
138 |
+ |
for (int i = nThreads; i-->0; ) |
139 |
+ |
p.execute(task); |
140 |
+ |
phaser.arriveAndAwaitAdvance(); |
141 |
+ |
phaser.arriveAndAwaitAdvance(); |
142 |
+ |
assertEquals(total, acc.get()); |
143 |
|
} |
144 |
|
} |
145 |
|
|