rpc.turbo.loadbalance.RandomLoadBalance Maven / Gradle / Ivy
The newest version!
package rpc.turbo.loadbalance;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
/**
* 速度略慢 115.069 ± 1.193 ops/us
*
* @author Hank
*
* @param
* 必须为Weightable子类
*/
public class RandomLoadBalance implements LoadBalance {
protected volatile WeightableGroup weightableGroup = null;
@Override
public void setWeightables(List weightables) {
weightableGroup = new WeightableGroup<>(weightables);
}
@Override
public T select() {
final WeightableGroup weightableGroup = this.weightableGroup;
if (weightableGroup == null) {
return null;
}
int sum = weightableGroup.sum();
if (sum < 2) {
return weightableGroup.get(0);
}
int seed = ThreadLocalRandom.current().nextInt(sum + 1);
return weightableGroup.get(seed);
}
}