Skip to content

Commit

Permalink
Merge pull request #323 from pacoyi/AvoidOverflow
Browse files Browse the repository at this point in the history
Avoid overflow
  • Loading branch information
qiangdavidliu authored Nov 8, 2017
2 parents 2d96971 + 53a2c7d commit f8bb8ea
Showing 1 changed file with 18 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,22 @@ public List<Server> getEligibleServers(List<Server> servers, Object loadBalancer
return results;
}
}

/**
* Referenced from RoundRobinRule
* Inspired by the implementation of {@link AtomicInteger#incrementAndGet()}.
*
* @param modulo The modulo to bound the value of the counter.
* @return The next value.
*/
private int incrementAndGetModulo(int modulo) {
for (;;) {
int current = nextIndex.get();
int next = (current + 1) % modulo;
if (nextIndex.compareAndSet(current, next))
return current;
}
}

/**
* Choose a random server after the predicate filters a list of servers. Load balancer key
Expand All @@ -160,7 +176,7 @@ public Optional<Server> chooseRoundRobinAfterFiltering(List<Server> servers) {
if (eligible.size() == 0) {
return Optional.absent();
}
return Optional.of(eligible.get(nextIndex.getAndIncrement() % eligible.size()));
return Optional.of(eligible.get(incrementAndGetModulo(eligible.size())));
}

/**
Expand All @@ -184,7 +200,7 @@ public Optional<Server> chooseRoundRobinAfterFiltering(List<Server> servers, Obj
if (eligible.size() == 0) {
return Optional.absent();
}
return Optional.of(eligible.get(nextIndex.getAndIncrement() % eligible.size()));
return Optional.of(eligible.get(incrementAndGetModulo(eligible.size())));
}

/**
Expand Down

0 comments on commit f8bb8ea

Please sign in to comment.