forked from winterbe/java8-tutorial
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongAdder1.java
More file actions
43 lines (30 loc) · 1.15 KB
/
LongAdder1.java
File metadata and controls
43 lines (30 loc) · 1.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package com.winterbe.java8.samples.concurrent;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.LongAdder;
import java.util.stream.IntStream;
/**
* @author Benjamin Winterberg
*/
public class LongAdder1 {
private static final int NUM_INCREMENTS = 10000;
private static LongAdder adder = new LongAdder();
public static void main(String[] args) {
testIncrement();
testAdd();
}
private static void testAdd() {
ExecutorService executor = Executors.newFixedThreadPool(2);
IntStream.range(0, NUM_INCREMENTS)
.forEach(i -> executor.submit(() -> adder.add(2)));
ConcurrentUtils.stop(executor);
System.out.format("Add: %d\n", adder.sumThenReset());
}
private static void testIncrement() {
ExecutorService executor = Executors.newFixedThreadPool(2);
IntStream.range(0, NUM_INCREMENTS)
.forEach(i -> executor.submit(adder::increment));
ConcurrentUtils.stop(executor);
System.out.format("Increment: Expected=%d; Is=%d\n", NUM_INCREMENTS, adder.sumThenReset());
}
}