Skip to content

Commit e98f201

Browse files
committed
Atomic accumulate
1 parent e8cc2fc commit e98f201

File tree

1 file changed

+25
-4
lines changed

1 file changed

+25
-4
lines changed

src/com/winterbe/java8/samples/concurrent/Atomic1.java

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import java.util.concurrent.ExecutorService;
44
import java.util.concurrent.Executors;
55
import java.util.concurrent.atomic.AtomicInteger;
6+
import java.util.function.IntBinaryOperator;
67
import java.util.stream.IntStream;
78

89
/**
@@ -12,23 +13,43 @@ public class Atomic1 {
1213

1314
private static final int NUM_INCREMENTS = 10000;
1415

15-
private static AtomicInteger count = new AtomicInteger(0);
16+
private static AtomicInteger atomicInt = new AtomicInteger(0);
1617

1718
public static void main(String[] args) {
1819
testIncrement();
20+
testAccumulate();
21+
}
22+
23+
private static void testAccumulate() {
24+
atomicInt.set(0);
25+
26+
ExecutorService executor = Executors.newFixedThreadPool(2);
27+
28+
IntStream.range(0, NUM_INCREMENTS)
29+
.forEach(i -> {
30+
Runnable task = () -> {
31+
IntBinaryOperator operator = (a, b) -> a + b;
32+
atomicInt.accumulateAndGet(i, operator);
33+
};
34+
executor.submit(task);
35+
});
36+
37+
ConcurrentUtils.stop(executor);
38+
39+
System.out.format("Accumulate: %d\n", atomicInt.get());
1940
}
2041

2142
private static void testIncrement() {
22-
count.set(0);
43+
atomicInt.set(0);
2344

2445
ExecutorService executor = Executors.newFixedThreadPool(2);
2546

2647
IntStream.range(0, NUM_INCREMENTS)
27-
.forEach(i -> executor.submit(count::incrementAndGet));
48+
.forEach(i -> executor.submit(atomicInt::incrementAndGet));
2849

2950
ConcurrentUtils.stop(executor);
3051

31-
System.out.format("Expected=%d; Is=%d", NUM_INCREMENTS, count.get());
52+
System.out.format("Increment: Expected=%d; Is=%d\n", NUM_INCREMENTS, atomicInt.get());
3253
}
3354

3455
}

0 commit comments

Comments
 (0)