if (leastActive == -1 || active < leastActive) { // Restart, when find a invoker having smaller least active value.
//初始化或者找到一个活跃数更小invoker leastActive = active; // Record the current least active value leastCount = 1; // Reset leastCount, count again based on current leastCount leastIndexs[0] = i; // Reset totalWeight = weight; // Reset firstWeight = weight; // Record the weight the first invoker sameWeight = true; // Reset, every invoker has the same weight value? } elseif (active == leastActive) { // If current invoker's active value equals with leaseActive, then accumulating.
//具有相同活跃数的invoker,累加他们的权重 leastIndexs[leastCount++] = i; // Record index number of this invoker totalWeight += weight; // Add this invoker's weight to totalWeight.
//问题2:优化判断i>0 // If every invoker has the same weight? if (sameWeight && i > 0 && weight != firstWeight) { sameWeight = false; } } }
//最小活跃数invoker只有一个,直接返回 // assert(leastCount > 0) if (leastCount == 1) { // If we got exactly one invoker having the least active value, return this invoker directly. return invokers.get(leastIndexs[0]); }
//加权随机实现:具备相同最小活跃数的不同权重invoker列表获取 if (!sameWeight && totalWeight > 0) {
//问题3:使用ThreadLocalRandom.current()替换 // If (not every invoker has the same weight & at least one invoker's weight>0), select randomly based on totalWeight. intoffsetWeight= random.nextInt(totalWeight);
// Return a invoker based on the random value. for (inti=0; i < leastCount; i++) {
//问题4:<=0可能没有遍历完数组就返回了,导致最后一个invoker没有机会被选到。栗子:5,2,1。offsetWeight=7 if (offsetWeight <= 0) return invokers.get(leastIndex); } }
//随机返回一个invoker // If all invokers have the same weight value or totalWeight=0, return evenly. return invokers.get(leastIndexs[random.nextInt(leastCount)]); }