File tree 1 file changed +43
-0
lines changed
src/com/winterbe/java8/samples/concurrent
1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments