Skip to content

Commit 765da5b

Browse files
committed
bael-8622 getAndIncrement - fix based on email feedback
I believe there is a mistake in the code in Section 6 of the article https://www.baeldung.com/java-atomicinteger-load-balancer Specifically, the current code is: public String getServer() { int index = counter.get() % serverList.size(); counter.incrementAndGet(); return serverList.get(index); } But I believe the correct code should be: public String getServer() { int index = counter.getAndIncrement() % serverList.size(); return serverList.get(index); } In the current code of the article, several threads could be calling getServer() at the same time, execute counter.get() in sequence, all get the same server number (index), before each incrementing the counter. This would mean one server gets more uses, and other servers are skipped, breaking a fair round-robin strategy.
1 parent 9cb9838 commit 765da5b

File tree

1 file changed

+1
-2
lines changed

1 file changed

+1
-2
lines changed

core-java-modules/core-java-concurrency-advanced-6/src/main/java/com/baeldung/atomic/AtomicLoadBalancer.java

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,7 @@ public AtomicLoadBalancer(List<String> serverList) {
1212
}
1313

1414
public String getServer() {
15-
int index = counter.get() % serverList.size();
16-
counter.incrementAndGet();
15+
int index = counter.getAndIncrement() % serverList.size();
1716
return serverList.get(index);
1817
}
1918

0 commit comments

Comments
 (0)