@Override
    protected ServiceInstance doChoose(String serviceName, List<ServiceInstance> instances) {
        // The minimum number of instances with the same number of concurrent instances
        int sameActiveCount = 0;
        long minActiveRequest = -1;

        // Record the subscript for the least instance
        final int[] activeIndexes = new int[instances.size()];
        for (int index = 0, size = instances.size(); index < size; index++) {
            final ServiceInstance serviceInstance = instances.get(index);
            final InstanceStats instanceStats = ServiceStatsManager.INSTANCE.getInstanceStats(serviceInstance);
            final long activeRequest = instanceStats.getActiveRequests();
            if (minActiveRequest == -1 || activeRequest < minActiveRequest) {
                minActiveRequest = activeRequest;
                sameActiveCount = 1;
                activeIndexes[0] = index;
            } else if (minActiveRequest == activeRequest) {
                activeIndexes[sameActiveCount++] = index;
            }
        }

        // There is just the least concurrent instance
        if (sameActiveCount == 1) {
            return instances.get(activeIndexes[0]);
        }

        // Multiple identical concurrent instances are selected from a random strategy
        return instances.get(activeIndexes[ThreadLocalRandom.current().nextInt(sameActiveCount)]);
    }
@Test
    public void doChoose() {
        final BestAvailableLoadbalancer bestAvailableLoadbalancer = new BestAvailableLoadbalancer();
        int port1 = 9999;
        int port2 = 8888;
        String serviceName = "lb";
        final ServiceInstance serviceInstance1 = CommonUtils.buildInstance(serviceName, port1);
        final ServiceInstance serviceInstance2 = CommonUtils.buildInstance(serviceName, port2);
        final ServiceStats serviceStats = ServiceStatsManager.INSTANCE.getServiceStats(serviceName);
        final InstanceStats stats1 = serviceStats.getStats(serviceInstance1);
        for (int i = 0; i < 10; i++) {
            // Simulated instance 1 already has multiple concurrent requests
            stats1.beforeRequest();
        }
        final List<ServiceInstance> serviceInstances = Arrays.asList(serviceInstance1, serviceInstance2);

        // Simulate 100 requests, and instances with low concurrency will be more likely to be selected
        int count1 = 0, count2 = 0;
        for (int i = 0; i < 100; i++) {
            final Optional<ServiceInstance> choose = bestAvailableLoadbalancer.choose(serviceName, serviceInstances);
            Assert.assertTrue(choose.isPresent());
            if (choose.get().getPort() == port1) {
                count1++;
            } else {
                count2++;
            }
        }
        Assert.assertTrue(count1 < count2);
    }