Skip to content

Commit e03420c

Browse files
committed
Add LongAdder example
1 parent fe4fd80 commit e03420c

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package com.winterbe.java8.samples.concurrent;
2+
3+
import java.util.concurrent.ExecutorService;
4+
import java.util.concurrent.Executors;
5+
import java.util.concurrent.atomic.LongAdder;
6+
import java.util.stream.IntStream;
7+
8+
/**
9+
* @author Benjamin Winterberg
10+
*/
11+
public class LongAdder1 {
12+
13+
private static final int NUM_INCREMENTS = 10000;
14+
15+
private static LongAdder adder = new LongAdder();
16+
17+
public static void main(String[] args) {
18+
testIncrement();
19+
testAdd();
20+
}
21+
22+
private static void testAdd() {
23+
ExecutorService executor = Executors.newFixedThreadPool(2);
24+
25+
IntStream.range(0, NUM_INCREMENTS)
26+
.forEach(i -> executor.submit(() -> adder.add(2)));
27+
28+
ConcurrentUtils.stop(executor);
29+
30+
System.out.format("Add: %d\n", adder.sumThenReset());
31+
}
32+
33+
private static void testIncrement() {
34+
ExecutorService executor = Executors.newFixedThreadPool(2);
35+
36+
IntStream.range(0, NUM_INCREMENTS)
37+
.forEach(i -> executor.submit(adder::increment));
38+
39+
ConcurrentUtils.stop(executor);
40+
41+
System.out.format("Increment: Expected=%d; Is=%d\n", NUM_INCREMENTS, adder.sumThenReset());
42+
}
43+
}

0 commit comments

Comments
 (0)