This is an automated email from the ASF dual-hosted git repository.

albumenj pushed a commit to branch 3.2
in repository https://gitbox.apache.org/repos/asf/dubbo.git


The following commit(s) were added to refs/heads/3.2 by this push:
     new b967d3c1f8 binary search weights Fixes 11776 (#11886)
b967d3c1f8 is described below

commit b967d3c1f83265f99b1b86303ccf4899ec4ee072
Author: eye-gu <[email protected]>
AuthorDate: Tue Mar 28 15:34:45 2023 +0800

    binary search weights Fixes 11776 (#11886)
    
    Co-authored-by: eye <[email protected]>
---
 .../rpc/cluster/loadbalance/RandomLoadBalance.java   | 20 +++++++++++++++++---
 1 file changed, 17 insertions(+), 3 deletions(-)

diff --git 
a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/RandomLoadBalance.java
 
b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/RandomLoadBalance.java
index cc06c0d902..ce5bdaa16c 100644
--- 
a/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/RandomLoadBalance.java
+++ 
b/dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/loadbalance/RandomLoadBalance.java
@@ -22,6 +22,7 @@ import org.apache.dubbo.rpc.Invocation;
 import org.apache.dubbo.rpc.Invoker;
 import org.apache.dubbo.rpc.cluster.ClusterInvoker;
 
+import java.util.Arrays;
 import java.util.List;
 import java.util.concurrent.ThreadLocalRandom;
 
@@ -79,10 +80,23 @@ public class RandomLoadBalance extends AbstractLoadBalance {
             // If (not every invoker has the same weight & at least one 
invoker's weight>0), select randomly based on totalWeight.
             int offset = ThreadLocalRandom.current().nextInt(totalWeight);
             // Return an invoker based on the random value.
-            for (int i = 0; i < length; i++) {
-                if (offset < weights[i]) {
-                    return invokers.get(i);
+            if (length <= 4) {
+                for (int i = 0; i < length; i++) {
+                    if (offset < weights[i]) {
+                        return invokers.get(i);
+                    }
                 }
+            } else {
+                int i = Arrays.binarySearch(weights, offset);
+                if (i < 0) {
+                    i = -i - 1;
+                } else {
+                    while (weights[i+1] == offset) {
+                        i++;
+                    }
+                    i++;
+                }
+                return invokers.get(i);
             }
         }
         // If all invokers have the same weight value or totalWeight=0, return 
evenly.

Reply via email to