From beaa402ff743d01791de3c9e43a106fc0a43ffdd Mon Sep 17 00:00:00 2001 From: wangwei Date: Fri, 8 May 2020 21:53:53 +0800 Subject: [PATCH] [ISSUE #2765]Optimize MemberUtils class's kRandom method --- .../nacos/core/cluster/MemberUtils.java | 25 +++++++++++-------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/core/src/main/java/com/alibaba/nacos/core/cluster/MemberUtils.java b/core/src/main/java/com/alibaba/nacos/core/cluster/MemberUtils.java index a9aa1933e..f632a3044 100644 --- a/core/src/main/java/com/alibaba/nacos/core/cluster/MemberUtils.java +++ b/core/src/main/java/com/alibaba/nacos/core/cluster/MemberUtils.java @@ -19,6 +19,7 @@ package com.alibaba.nacos.core.cluster; import com.alibaba.nacos.common.utils.ExceptionUtil; import com.alibaba.nacos.core.utils.ApplicationUtils; import com.alibaba.nacos.core.utils.Loggers; +import java.util.concurrent.ThreadLocalRandom; import org.apache.commons.lang3.StringUtils; import java.time.LocalDateTime; @@ -139,19 +140,21 @@ public class MemberUtils { int k = ApplicationUtils .getProperty("nacos.core.member.report.random-num", Integer.class, 3); - Set tmp = new HashSet<>(); + Set kMembers = new HashSet<>(); - // Here thinking similar consul gossip protocols random k node - int totalSize = members.size(); - for (int i = 0; i < 3 * totalSize && tmp.size() <= k; i++) { - for (Member member : members) { - if (filter.test(member)) { - tmp.add(member); - } - } - } + // Here thinking similar consul gossip protocols random k node + int totalSize = members.size(); + Member[] membersArray = members.toArray(new Member[totalSize]); + ThreadLocalRandom threadLocalRandom = ThreadLocalRandom.current(); + for (int i = 0; i < 3 * totalSize && kMembers.size() < k; i++) { + int idx = threadLocalRandom.nextInt(totalSize); + Member member = membersArray[idx]; + if (filter.test(member)) { + kMembers.add(member); + } + } - return tmp; + return kMembers; } // 默认配置格式解析,只有nacos-server的ip or ip:port or hostname:port 信息