Skip to content

Commit 65246ae

Browse files
author
Bruce Eckel
committed
changed to AtomicInteger
1 parent 620703e commit 65246ae

File tree

1 file changed

+7
-5
lines changed

1 file changed

+7
-5
lines changed

concurrent/ParallelStreamPuzzle2.java

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,18 +6,20 @@
66
import java.util.function.*;
77
import java.util.stream.*;
88
import java.util.concurrent.*;
9+
import java.util.concurrent.atomic.*;
910
import java.nio.file.*;
1011

1112
public class ParallelStreamPuzzle2 {
1213
public static Deque<String> trace =
1314
new ConcurrentLinkedDeque<>();
1415
static class
1516
IntGenerator implements Supplier<Integer> {
16-
private int current = 0;
17-
public synchronized Integer get() { // [1]
18-
trace.add(current + ": " +
17+
private AtomicInteger current =
18+
new AtomicInteger();
19+
public Integer get() {
20+
trace.add(current.get() + ": " +
1921
Thread.currentThread().getName());
20-
return current++;
22+
return current.getAndIncrement();
2123
}
2224
}
2325
public static void
@@ -32,5 +34,5 @@ public synchronized Integer get() { // [1]
3234
}
3335
}
3436
/* Output:
35-
[2, 3, 4, 5, 6, 7, 8, 9, 10, 63]
37+
[4, 25, 27, 32, 37, 44, 49, 56, 61, 73]
3638
*/

0 commit comments

Comments
 (0)