private static int findRandomPort()

in 2-advanced/dubbo-samples-migration/dubbo-samples-migration-case-application/dubbo-samples-migration-case-application-provider/src/main/java/org/apache/dubbo/migration/EmbeddedZooKeeper.java [267:299]


    private static int findRandomPort(int min, int max) {
        if (min < 1024) {
            throw new IllegalArgumentException("Max port shouldn't be less than 1024.");
        }

        if (max > 65535) {
            throw new IllegalArgumentException("Max port shouldn't be greater than 65535.");
        }

        if (min > max) {
            throw new IllegalArgumentException("Min port shouldn't be greater than max port.");
        }

        int port = 0;
        int counter = 0;

        // Workaround for legacy JDK doesn't support Random.nextInt(min, max).
        List<Integer> randomInts = RANDOM.ints(min, max + 1)
                .limit(max - min)
                .mapToObj(Integer::valueOf)
                .collect(Collectors.toList());

        do {
            if (counter > max - min) {
                throw new IllegalStateException("Unable to find a port between " + min + "-" + max);
            }

            port = randomInts.get(counter);
            counter++;
        } while (isPortInUse(port));

        return port;
    }