demery-pivotal opened a new pull request #5425:
URL: https://github.com/apache/geode/pull/5425


   Co-Authored-by  Jacob Barrett <jbarr...@pivotal.io>
   Co-Authored-by: Dale Emery <dem...@vmware.com>
   
   diff --git 
a/geode-core/src/distributedTest/java/org/apache/geode/cache30/ReconnectWithClusterConfigurationDUnitTest.java
 
b/geode-core/src/distributedTest/java/org/apache/geode/cache30/ReconnectWithClusterConfigurationDUnitTest.java
   index 1c8f92c282..cc66ac198b 100644
   --- 
a/geode-core/src/distributedTest/java/org/apache/geode/cache30/ReconnectWithClusterConfigurationDUnitTest.java
   +++ 
b/geode-core/src/distributedTest/java/org/apache/geode/cache30/ReconnectWithClusterConfigurationDUnitTest.java
   @@ -33,7 +33,6 @@ import java.io.IOException;
    import java.io.Serializable;
    import java.net.UnknownHostException;
    import java.nio.file.Paths;
   -import java.util.List;
    import java.util.Properties;
    import java.util.concurrent.TimeUnit;
   
   @@ -49,7 +48,6 @@ import org.apache.geode.distributed.DistributedSystem;
    import org.apache.geode.distributed.Locator;
    import org.apache.geode.distributed.internal.InternalLocator;
    import 
org.apache.geode.distributed.internal.membership.api.MembershipManagerHelper;
   -import org.apache.geode.internal.AvailablePort;
    import org.apache.geode.internal.AvailablePortHelper;
    import org.apache.geode.internal.inet.LocalHostUtil;
    import org.apache.geode.test.awaitility.GeodeAwaitility;
   @@ -79,18 +77,12 @@ public class ReconnectWithClusterConfigurationDUnitTest 
implements Serializable
   
      @Before
      public void setup() throws IOException {
   -    List<AvailablePort.Keeper> randomAvailableTCPPortKeepers =
   -        AvailablePortHelper.getRandomAvailableTCPPortKeepers(NUM_LOCATORS);
   -    for (int i = 0; i < NUM_LOCATORS; i++) {
   -      AvailablePort.Keeper keeper = randomAvailableTCPPortKeepers.get(i);
   -      locatorPorts[i] = keeper.getPort();
   -    }
   +    locatorPorts = 
AvailablePortHelper.getRandomAvailableTCPPorts(NUM_LOCATORS);
        final int[] locPorts = locatorPorts;
        Invoke.invokeInEveryVM("set locator ports", () -> locatorPorts = 
locPorts);
        for (int i = 0; i < NUM_LOCATORS; i++) {
          final String workingDir = 
temporaryFolder.newFolder().getAbsolutePath();
          final int locatorNumber = i;
   -      randomAvailableTCPPortKeepers.get(locatorNumber).release();
          VM.getVM(i).invoke("start locator", () -> {
            try {
              Disconnect.disconnectFromDS();
   diff --git 
a/geode-core/src/distributedTest/java/org/apache/geode/distributed/DistributedSystemDUnitTest.java
 
b/geode-core/src/distributedTest/java/org/apache/geode/distributed/DistributedSystemDUnitTest.java
   index bde5458fd6..5bdf35c950 100644
   --- 
a/geode-core/src/distributedTest/java/org/apache/geode/distributed/DistributedSystemDUnitTest.java
   +++ 
b/geode-core/src/distributedTest/java/org/apache/geode/distributed/DistributedSystemDUnitTest.java
   @@ -102,7 +102,7 @@ public class DistributedSystemDUnitTest extends 
JUnit4DistributedTestCase {
        this.locatorPort = getRandomAvailablePort(SOCKET);
        this.tcpPort = getRandomAvailablePort(SOCKET);
   
   -    int[] portRange = getRandomAvailableTCPPortRange(3, true);
   +    int[] portRange = getRandomAvailableTCPPortRange(3);
        this.lowerBoundOfPortRange = portRange[0];
        this.upperBoundOfPortRange = portRange[portRange.length - 1];
      }
   diff --git 
a/geode-core/src/distributedTest/java/org/apache/geode/distributed/LocatorDUnitTest.java
 
b/geode-core/src/distributedTest/java/org/apache/geode/distributed/LocatorDUnitTest.java
   index 2a01cd6430..4d86091fe5 100644
   --- 
a/geode-core/src/distributedTest/java/org/apache/geode/distributed/LocatorDUnitTest.java
   +++ 
b/geode-core/src/distributedTest/java/org/apache/geode/distributed/LocatorDUnitTest.java
   @@ -1115,13 +1115,12 @@ public class LocatorDUnitTest implements 
Serializable {
   
      @Test
      public void testConcurrentLocatorStartup() throws Exception {
   -    List<AvailablePort.Keeper> portKeepers =
   -        AvailablePortHelper.getRandomAvailableTCPPortKeepers(4);
   +    final int[] ports = AvailablePortHelper.getRandomAvailableTCPPorts(4);
        StringBuilder sb = new StringBuilder(100);
   -    for (int i = 0; i < portKeepers.size(); i++) {
   -      AvailablePort.Keeper keeper = portKeepers.get(i);
   -      sb.append("localhost[").append(keeper.getPort()).append("]");
   -      if (i < portKeepers.size() - 1) {
   +    for (int i = 0; i < ports.length; i++) {
   +      final int port = ports[i];
   +      sb.append("localhost[").append(port).append("]");
   +      if (i < ports.length - 1) {
            sb.append(',');
          }
        }
   @@ -1129,12 +1128,10 @@ public class LocatorDUnitTest implements 
Serializable {
   
        Properties dsProps = getClusterProperties(locators, "false");
   
   -    List<AsyncInvocation<Object>> asyncInvocations = new 
ArrayList<>(portKeepers.size());
   +    List<AsyncInvocation<Object>> asyncInvocations = new 
ArrayList<>(ports.length);
   
   -    for (int i = 0; i < portKeepers.size(); i++) {
   -      AvailablePort.Keeper keeper = portKeepers.get(i);
   -      int port = keeper.getPort();
   -      keeper.release();
   +    for (int i = 0; i < ports.length; i++) {
   +      final int port = ports[i];
          AsyncInvocation<Object> startLocator = getVM(i).invokeAsync("start 
locator " + i, () -> {
            DUnitBlackboard blackboard = getBlackboard();
            blackboard.signalGate("" + port);
   diff --git 
a/geode-core/src/distributedTest/java/org/apache/geode/internal/cache/GridAdvisorDUnitTest.java
 
b/geode-core/src/distributedTest/java/org/apache/geode/internal/cache/GridAdvisorDUnitTest.java
   index 9774f5c191..8aeeba2186 100644
   --- 
a/geode-core/src/distributedTest/java/org/apache/geode/internal/cache/GridAdvisorDUnitTest.java
   +++ 
b/geode-core/src/distributedTest/java/org/apache/geode/internal/cache/GridAdvisorDUnitTest.java
   @@ -41,7 +41,6 @@ import org.apache.geode.cache.server.CacheServer;
    import org.apache.geode.distributed.Locator;
    import org.apache.geode.distributed.internal.DistributionAdvisee;
    import org.apache.geode.distributed.internal.InternalLocator;
   -import org.apache.geode.internal.AvailablePort.Keeper;
    import org.apache.geode.internal.AvailablePortHelper;
    import org.apache.geode.logging.internal.log4j.api.LogService;
    import org.apache.geode.test.dunit.NetworkUtils;
   @@ -71,19 +70,13 @@ public class GridAdvisorDUnitTest extends 
JUnit4DistributedTestCase {
        VM vm2 = VM.getVM(2);
        VM vm3 = VM.getVM(3);
   
   -    List<Keeper> freeTCPPorts = 
AvailablePortHelper.getRandomAvailableTCPPortKeepers(6);
   -    final Keeper keeper1 = freeTCPPorts.get(0);
   -    final int port1 = keeper1.getPort();
   -    final Keeper keeper2 = freeTCPPorts.get(1);
   -    final int port2 = keeper2.getPort();
   -    final Keeper bsKeeper1 = freeTCPPorts.get(2);
   -    final int bsPort1 = bsKeeper1.getPort();
   -    final Keeper bsKeeper2 = freeTCPPorts.get(3);
   -    final int bsPort2 = bsKeeper2.getPort();
   -    final Keeper bsKeeper3 = freeTCPPorts.get(4);
   -    final int bsPort3 = bsKeeper3.getPort();
   -    final Keeper bsKeeper4 = freeTCPPorts.get(5);
   -    final int bsPort4 = bsKeeper4.getPort();
   +    int[] freeTCPPorts = AvailablePortHelper.getRandomAvailableTCPPorts(6);
   +    final int port1 = freeTCPPorts[0];
   +    final int port2 = freeTCPPorts[1];
   +    final int bsPort1 = freeTCPPorts[2];
   +    final int bsPort2 = freeTCPPorts[3];
   +    final int bsPort3 = freeTCPPorts[4];
   +    final int bsPort4 = freeTCPPorts[5];
   
        final String host0 = NetworkUtils.getServerHostName();
        final String locators = host0 + "[" + port1 + "]" + "," + host0 + "[" + 
port2 + "]";
   @@ -94,22 +87,16 @@ public class GridAdvisorDUnitTest extends 
JUnit4DistributedTestCase {
        dsProps.setProperty(LOG_LEVEL, String.valueOf(logger.getLevel()));
        dsProps.setProperty(ENABLE_CLUSTER_CONFIGURATION, "false");
   
   -    keeper1.release();
        vm0.invoke(() -> startLocatorOnPort(port1, dsProps, null));
   
   -    keeper2.release();
        vm3.invoke(() -> startLocatorOnPort(port2, dsProps, "locator2HNFC"));
   
        vm1.invoke(() -> createCache(locators, null));
        vm2.invoke(() -> createCache(locators, null));
   
   -    bsKeeper1.release();
        vm1.invoke(() -> startBridgeServerOnPort(bsPort1, "bs1Group1", 
"bs1Group2"));
   -    bsKeeper3.release();
        vm1.invoke(() -> startBridgeServerOnPort(bsPort3, "bs3Group1", 
"bs3Group2"));
   -    bsKeeper2.release();
        vm2.invoke(() -> startBridgeServerOnPort(bsPort2, "bs2Group1", 
"bs2Group2"));
   -    bsKeeper4.release();
        vm2.invoke(() -> startBridgeServerOnPort(bsPort4, "bs4Group1", 
"bs4Group2"));
   
        // verify that locators know about each other
   @@ -210,19 +197,13 @@ public class GridAdvisorDUnitTest extends 
JUnit4DistributedTestCase {
        VM vm2 = VM.getVM(2);
        VM vm3 = VM.getVM(3);
   
   -    List<Keeper> freeTCPPorts = 
AvailablePortHelper.getRandomAvailableTCPPortKeepers(6);
   -    final Keeper keeper1 = freeTCPPorts.get(0);
   -    final int port1 = keeper1.getPort();
   -    final Keeper keeper2 = freeTCPPorts.get(1);
   -    final int port2 = keeper2.getPort();
   -    final Keeper bsKeeper1 = freeTCPPorts.get(2);
   -    final int bsPort1 = bsKeeper1.getPort();
   -    final Keeper bsKeeper2 = freeTCPPorts.get(3);
   -    final int bsPort2 = bsKeeper2.getPort();
   -    final Keeper bsKeeper3 = freeTCPPorts.get(4);
   -    final int bsPort3 = bsKeeper3.getPort();
   -    final Keeper bsKeeper4 = freeTCPPorts.get(5);
   -    final int bsPort4 = bsKeeper4.getPort();
   +    int[] freeTCPPorts = AvailablePortHelper.getRandomAvailableTCPPorts(6);
   +    final int port1 = freeTCPPorts[0];
   +    final int port2 = freeTCPPorts[1];
   +    final int bsPort1 = freeTCPPorts[2];
   +    final int bsPort2 = freeTCPPorts[3];
   +    final int bsPort3 = freeTCPPorts[4];
   +    final int bsPort4 = freeTCPPorts[5];
   
        final String host0 = NetworkUtils.getServerHostName();
        final String locators = host0 + "[" + port1 + "]" + "," + host0 + "[" + 
port2 + "]";
   @@ -233,22 +214,16 @@ public class GridAdvisorDUnitTest extends 
JUnit4DistributedTestCase {
        dsProps.setProperty(LOG_LEVEL, String.valueOf(logger.getLevel()));
        dsProps.setProperty(ENABLE_CLUSTER_CONFIGURATION, "false");
   
   -    keeper1.release();
        vm0.invoke(() -> startLocatorOnPort(port1, dsProps, null));
   
   -    keeper2.release();
        vm3.invoke(() -> startLocatorOnPort(port2, dsProps, "locator2HNFC"));
   
        vm1.invoke(() -> createCache(locators, "bs1Group1, bs1Group2"));
        vm2.invoke(() -> createCache(locators, "bs2Group1, bs2Group2"));
   
   -    bsKeeper1.release();
        vm1.invoke(() -> startBridgeServerOnPort(bsPort1));
   -    bsKeeper3.release();
        vm1.invoke(() -> startBridgeServerOnPort(bsPort3));
   -    bsKeeper2.release();
        vm2.invoke(() -> startBridgeServerOnPort(bsPort2));
   -    bsKeeper4.release();
        vm2.invoke(() -> startBridgeServerOnPort(bsPort4));
   
        // verify that locators know about each other
   diff --git 
a/geode-core/src/integrationTest/java/org/apache/geode/internal/AvailablePortHelperIntegrationTest.java
 
b/geode-core/src/integrationTest/java/org/apache/geode/internal/AvailablePortHelperIntegrationTest.java
   index 1f1199a261..a128d2a8e7 100644
   --- 
a/geode-core/src/integrationTest/java/org/apache/geode/internal/AvailablePortHelperIntegrationTest.java
   +++ 
b/geode-core/src/integrationTest/java/org/apache/geode/internal/AvailablePortHelperIntegrationTest.java
   @@ -15,18 +15,10 @@
    package org.apache.geode.internal;
   
    import static java.util.Arrays.stream;
   -import static java.util.Comparator.naturalOrder;
   -import static 
org.apache.geode.distributed.internal.DistributionConfig.DEFAULT_MEMBERSHIP_PORT_RANGE;
   -import static 
org.apache.geode.internal.AvailablePort.AVAILABLE_PORTS_LOWER_BOUND;
   -import static 
org.apache.geode.internal.AvailablePort.AVAILABLE_PORTS_UPPER_BOUND;
    import static org.apache.geode.internal.AvailablePort.MULTICAST;
   -import static 
org.apache.geode.internal.AvailablePortHelper.getRandomAvailableTCPPortRange;
   -import static 
org.apache.geode.internal.AvailablePortHelper.getRandomAvailableTCPPortRangeKeepers;
    import static 
org.apache.geode.internal.AvailablePortHelper.getRandomAvailableTCPPorts;
    import static 
org.apache.geode.internal.AvailablePortHelper.getRandomAvailableUDPPort;
   -import static 
org.apache.geode.internal.AvailablePortHelper.initializeUniquePortRange;
    import static org.assertj.core.api.Assertions.assertThat;
   -import static org.junit.Assume.assumeFalse;
   
    import java.io.IOException;
    import java.io.UncheckedIOException;
   @@ -34,14 +26,10 @@ import java.net.InetSocketAddress;
    import java.net.ServerSocket;
    import java.util.Collection;
    import java.util.HashSet;
   -import java.util.List;
    import java.util.Set;
    import java.util.stream.Collectors;
   -import java.util.stream.IntStream;
   
    import junitparams.JUnitParamsRunner;
   -import junitparams.Parameters;
   -import junitparams.naming.TestCaseName;
    import org.junit.After;
    import org.junit.Before;
    import org.junit.Rule;
   @@ -49,9 +37,6 @@ import org.junit.Test;
    import org.junit.rules.ErrorCollector;
    import org.junit.runner.RunWith;
   
   -import org.apache.geode.internal.AvailablePort.Keeper;
   -import org.apache.geode.internal.lang.SystemUtils;
   -
    @RunWith(JUnitParamsRunner.class)
    public class AvailablePortHelperIntegrationTest {
   
   @@ -79,178 +64,45 @@ public class AvailablePortHelperIntegrationTest {
      }
   
      @Test
   -  public void getRandomAvailableTCPPortRange_returnsNoPorts_ifCountIsZero() 
{
   -    int[] results = getRandomAvailableTCPPortRange(0);
   +  public void getRandomAvailableTCPPorts_returnsNoPorts_ifCountIsZero() {
   +    int[] results = getRandomAvailableTCPPorts(0);
   
        assertThat(results)
            .isEmpty();
      }
   
      @Test
   -  public void getRandomAvailableTCPPortRange_returnsOnePort_ifCountIsOne() {
   -    int[] results = getRandomAvailableTCPPortRange(1);
   +  public void getRandomAvailableTCPPorts_returnsOnePort_ifCountIsOne() {
   +    int[] results = getRandomAvailableTCPPorts(1);
   
        assertThat(results)
            .hasSize(1);
      }
   
      @Test
   -  public void 
getRandomAvailableTCPPortRange_returnsManyPorts_ifCountIsMany() {
   -    int[] results = getRandomAvailableTCPPortRange(10);
   +  public void getRandomAvailableTCPPorts_returnsManyPorts_ifCountIsMany() {
   +    int[] results = getRandomAvailableTCPPorts(10);
   
        assertThat(results)
            .hasSize(10);
      }
   
      @Test
   -  @Parameters({"true", "false"})
   -  @TestCaseName("{method}(useMembershipPortRange={0})")
   -  public void getRandomAvailableTCPPortRange_returnsUsablePorts(boolean 
useMembershipPortRange) {
   -    int[] results = getRandomAvailableTCPPortRange(10, 
useMembershipPortRange);
   +  public void getRandomAvailableTCPPorts_returnsUsablePorts() {
   +    int[] results = getRandomAvailableTCPPorts(10);
   
        stream(results).forEach(port -> assertThatPort(port)
            .isUsable());
      }
   
      @Test
   -  @Parameters({"true", "false"})
   -  @TestCaseName("{method}(useMembershipPortRange={0})")
   -  public void getRandomAvailableTCPPortRange_returnsUniquePorts(boolean 
useMembershipPortRange) {
   -    int[] results = getRandomAvailableTCPPortRange(10, 
useMembershipPortRange);
   -
   -    assertThat(results)
   -        .doesNotHaveDuplicates();
   -  }
   -
   -  @Test
   -  @Parameters({"true", "false"})
   -  @TestCaseName("{method}(useMembershipPortRange={0})")
   -  public void getRandomAvailableTCPPortRange_returnsNaturallyOrderedPorts(
   -      boolean useMembershipPortRange) {
   -    int[] results = getRandomAvailableTCPPortRange(10, 
useMembershipPortRange);
   -
   -    assertThat(results)
   -        .isSortedAccordingTo(naturalOrder());
   -  }
   -
   -  @Test
   -  @Parameters({"true", "false"})
   -  @TestCaseName("{method}(useMembershipPortRange={0})")
   -  public void getRandomAvailableTCPPortRange_returnsConsecutivePorts(
   -      boolean useMembershipPortRange) {
   -    int[] results = getRandomAvailableTCPPortRange(10, 
useMembershipPortRange);
   -
   -    assertThatSequence(results)
   -        .isConsecutive();
   -  }
   -
   -  @Test
   -  @Parameters({"true", "false"})
   -  @TestCaseName("{method}(useMembershipPortRange={0})")
   -  public void getRandomAvailableTCPPortRange_returnsPortsInRange(boolean 
useMembershipPortRange) {
   -    int lower =
   -        useMembershipPortRange ? DEFAULT_MEMBERSHIP_PORT_RANGE[0] : 
AVAILABLE_PORTS_LOWER_BOUND;
   -    int upper =
   -        useMembershipPortRange ? DEFAULT_MEMBERSHIP_PORT_RANGE[1] : 
AVAILABLE_PORTS_UPPER_BOUND;
   -
   -    int[] results = getRandomAvailableTCPPortRange(10, 
useMembershipPortRange);
   -
   -    stream(results).forEach(port ->
   -
   -    assertThat(port)
   -        .isGreaterThanOrEqualTo(lower)
   -        .isLessThanOrEqualTo(upper));
   -  }
   -
   -  @Test
   -  public void 
getRandomAvailableTCPPortRangeKeepers_returnsNoKeepers_ifCountIsZero() {
   -    List<Keeper> results = getRandomAvailableTCPPortRangeKeepers(0);
   -
   -    assertThat(results)
   -        .isEmpty();
   -  }
   -
   -  @Test
   -  public void 
getRandomAvailableTCPPortRangeKeepers_returnsOneKeeper_ifCountIsOne() {
   -    List<Keeper> results = getRandomAvailableTCPPortRangeKeepers(1);
   +  public void getRandomAvailableTCPPorts_returnsUniquePorts() {
   +    int[] results = getRandomAvailableTCPPorts(10);
   
        assertThat(results)
   -        .hasSize(1);
   -  }
   -
   -  @Test
   -  public void 
getRandomAvailableTCPPortRangeKeepers_returnsManyKeepers_ifCountIsMany() {
   -    List<Keeper> results = getRandomAvailableTCPPortRangeKeepers(10);
   -
   -    assertThat(results)
   -        .hasSize(10);
   -  }
   -
   -  @Test
   -  @Parameters({"true", "false"})
   -  @TestCaseName("{method}(useMembershipPortRange={0})")
   -  public void getRandomAvailableTCPPortRangeKeepers_returnsUsableKeepers(
   -      boolean useMembershipPortRange) {
   -    List<Keeper> results = getRandomAvailableTCPPortRangeKeepers(10, 
useMembershipPortRange);
   -
   -    results.stream().forEach(keeper ->
   -
   -    assertThatKeeper(keeper)
   -        .isUsable());
   -  }
   -
   -  @Test
   -  @Parameters({"true", "false"})
   -  @TestCaseName("{method}(useMembershipPortRange={0})")
   -  public void getRandomAvailableTCPPortRangeKeepers_returnsUniqueKeepers(
   -      boolean useMembershipPortRange) {
   -    List<Keeper> results = getRandomAvailableTCPPortRangeKeepers(10, 
useMembershipPortRange);
   -
   -    assertThat(keeperPorts(results))
            .doesNotHaveDuplicates();
      }
   
   -  @Test
   -  @Parameters({"true", "false"})
   -  @TestCaseName("{method}(useMembershipPortRange={0})")
   -  public void 
getRandomAvailableTCPPortRangeKeepers_returnsNaturallyOrderedPorts(
   -      boolean useMembershipPortRange) {
   -    List<Keeper> results = getRandomAvailableTCPPortRangeKeepers(10, 
useMembershipPortRange);
   -
   -    assertThat(keeperPorts(results))
   -        .isSortedAccordingTo(naturalOrder());
   -  }
   -
   -  @Test
   -  @Parameters({"true", "false"})
   -  @TestCaseName("{method}(useMembershipPortRange={0})")
   -  public void getRandomAvailableTCPPortRangeKeepers_returnsConsecutivePorts(
   -      boolean useMembershipPortRange) {
   -    List<Keeper> results = getRandomAvailableTCPPortRangeKeepers(10, 
useMembershipPortRange);
   -
   -    assertThatSequence(keeperPorts(results))
   -        .isConsecutive();
   -  }
   -
   -  @Test
   -  @Parameters({"true", "false"})
   -  @TestCaseName("{method}(useMembershipPortRange={0})")
   -  public void getRandomAvailableTCPPortRangeKeepers_returnsPortsInRange(
   -      boolean useMembershipPortRange) {
   -    int lower =
   -        useMembershipPortRange ? DEFAULT_MEMBERSHIP_PORT_RANGE[0] : 
AVAILABLE_PORTS_LOWER_BOUND;
   -    int upper =
   -        useMembershipPortRange ? DEFAULT_MEMBERSHIP_PORT_RANGE[1] : 
AVAILABLE_PORTS_UPPER_BOUND;
   -
   -    List<Keeper> results = getRandomAvailableTCPPortRangeKeepers(10, 
useMembershipPortRange);
   -
   -    keeperPorts(results).forEach(port ->
   -
   -    assertThat(port)
   -        .isGreaterThanOrEqualTo(lower)
   -        .isLessThanOrEqualTo(upper));
   -  }
   -
      @Test
      public void getRandomAvailableUDPPort_returnsNonZeroUdpPort() {
        int udpPort = getRandomAvailableUDPPort();
   @@ -268,13 +120,11 @@ public class AvailablePortHelperIntegrationTest {
      }
   
      @Test
   -  @Parameters({"true", "false"})
   -  @TestCaseName("{method}(useMembershipPortRange={0})")
   -  public void getRandomAvailableTCPPortRange_returnsUniqueRanges(boolean 
useMembershipPortRange) {
   +  public void getRandomAvailableTCPPorts_returnsUniqueRanges() {
        Collection<Integer> previousPorts = new HashSet<>();
        for (int i = 0; i < 3; ++i) {
   
   -      int[] results = getRandomAvailableTCPPortRange(5, 
useMembershipPortRange);
   +      int[] results = getRandomAvailableTCPPorts(5);
   
          Collection<Integer> ports = toSet(results);
   
   @@ -286,13 +136,11 @@ public class AvailablePortHelperIntegrationTest {
      }
   
      @Test
   -  @Parameters({"true", "false"})
   -  @TestCaseName("{method}(useMembershipPortRange={0})")
   -  public void getRandomAvailableTCPPort_returnsUniqueValues(boolean 
useMembershipPortRange) {
   +  public void getRandomAvailableTCPPort_returnsUniqueValues() {
        Collection<Integer> previousPorts = new HashSet<>();
        for (int i = 0; i < 3; ++i) {
   
   -      int port = getRandomAvailableTCPPorts(1, useMembershipPortRange)[0];
   +      int port = getRandomAvailableTCPPorts(1)[0];
   
          assertThat(previousPorts)
              .doesNotContain(port);
   @@ -301,52 +149,6 @@ public class AvailablePortHelperIntegrationTest {
        }
      }
   
   -  @Test
   -  @Parameters({"true", "false"})
   -  @TestCaseName("{method}(useMembershipPortRange={0})")
   -  public void initializeUniquePortRange_returnSamePortsForSameRange(
   -      boolean useMembershipPortRange) {
   -    assumeFalse(
   -        "Windows has ports scattered throughout the range that makes this 
test difficult to pass consistently",
   -        SystemUtils.isWindows());
   -
   -    for (int i = 0; i < 3; ++i) {
   -
   -      initializeUniquePortRange(i);
   -      int[] previousPorts = getRandomAvailableTCPPorts(3, 
useMembershipPortRange);
   -
   -      initializeUniquePortRange(i);
   -      int[] ports = getRandomAvailableTCPPorts(3, useMembershipPortRange);
   -
   -      assertThat(ports)
   -          .isEqualTo(previousPorts);
   -    }
   -  }
   -
   -  @Test
   -  @Parameters({"true", "false"})
   -  @TestCaseName("{method}(useMembershipPortRange={0})")
   -  public void 
initializeUniquePortRange_willReturnUniquePortsForUniqueRanges(
   -      boolean useMembershipPortRange) {
   -    assumeFalse(
   -        "Windows has ports scattered throughout the range that makes this 
test difficult to pass consistently",
   -        SystemUtils.isWindows());
   -
   -    Collection<Integer> previousPorts = new HashSet<>();
   -    for (int i = 0; i < 3; ++i) {
   -
   -      initializeUniquePortRange(i);
   -      int[] results = getRandomAvailableTCPPorts(5, useMembershipPortRange);
   -
   -      Collection<Integer> ports = toSet(results);
   -
   -      assertThat(previousPorts)
   -          .doesNotContainAnyElementsOf(ports);
   -
   -      previousPorts.addAll(ports);
   -    }
   -  }
   -
      private ServerSocket createServerSocket() {
        try {
          ServerSocket serverSocket = new ServerSocket();
   @@ -357,40 +159,16 @@ public class AvailablePortHelperIntegrationTest {
        }
      }
   
   -  private List<Integer> toList(int[] integers) {
   -    return stream(integers)
   -        .boxed()
   -        .collect(Collectors.toList());
   -  }
   -
      private Set<Integer> toSet(int[] integers) {
        return stream(integers)
            .boxed()
            .collect(Collectors.toSet());
      }
   
   -  private List<Integer> keeperPorts(List<Keeper> keepers) {
   -    return keepers.stream()
   -        .map(Keeper::getPort)
   -        .collect(Collectors.toList());
   -  }
   -
      private PortAssertion assertThatPort(int port) {
        return new PortAssertion(port);
      }
   
   -  private KeeperAssertion assertThatKeeper(Keeper keeper) {
   -    return new KeeperAssertion(keeper);
   -  }
   -
   -  private SequenceAssertion assertThatSequence(int[] integers) {
   -    return new SequenceAssertion(toList(integers));
   -  }
   -
   -  private SequenceAssertion assertThatSequence(List<Integer> integers) {
   -    return new SequenceAssertion(integers);
   -  }
   -
      private class PortAssertion {
   
        private final int port;
   @@ -417,44 +195,4 @@ public class AvailablePortHelperIntegrationTest {
        }
      }
   
   -  private class KeeperAssertion {
   -
   -    private final Keeper keeper;
   -
   -    KeeperAssertion(Keeper keeper) {
   -      this.keeper = keeper;
   -    }
   -
   -    KeeperAssertion isUsable() {
   -      int port = keeper.getPort();
   -      keeper.release();
   -      assertThatPort(port).isUsable();
   -      return this;
   -    }
   -  }
   -
   -  private class SequenceAssertion {
   -
   -    private final List<Integer> actual;
   -
   -    SequenceAssertion(List<Integer> actual) {
   -      this.actual = actual;
   -      assertThat(actual)
   -          .isNotEmpty();
   -    }
   -
   -    SequenceAssertion isConsecutive() {
   -      int start = actual.get(0);
   -      int end = actual.get(actual.size() - 1);
   -
   -      List<Integer> expected = IntStream.rangeClosed(start, end)
   -          .boxed()
   -          .collect(Collectors.toList());
   -
   -      assertThat(actual)
   -          .isEqualTo(expected);
   -
   -      return this;
   -    }
   -  }
    }
   diff --git 
a/geode-core/src/integrationTest/java/org/apache/geode/internal/AvailablePortJUnitTest.java
 
b/geode-core/src/integrationTest/java/org/apache/geode/internal/AvailablePortJUnitTest.java
   index 505a98c385..66b1a34134 100644
   --- 
a/geode-core/src/integrationTest/java/org/apache/geode/internal/AvailablePortJUnitTest.java
   +++ 
b/geode-core/src/integrationTest/java/org/apache/geode/internal/AvailablePortJUnitTest.java
   @@ -58,6 +58,7 @@ public class AvailablePortJUnitTest {
        assertFalse(AvailablePort.isPortAvailable(port, AvailablePort.SOCKET,
            InetAddress.getByName(LOOPBACK_ADDRESS)));
   
   +
        InetAddress localHostAddress = InetAddress.getLocalHost();
        // The next assertion assumes that the local host address is not a 
loopback address. Skip the
        // assertion on host machines that don't satisfy the assumption.
   @@ -65,8 +66,7 @@ public class AvailablePortJUnitTest {
          assertTrue(AvailablePort.isPortAvailable(port, AvailablePort.SOCKET, 
localHostAddress));
        }
   
   -    // This should test all interfaces.
   -    assertFalse(AvailablePort.isPortAvailable(port, AvailablePort.SOCKET));
   +    assertFalse(AvailablePort.isPortAvailable(port, AvailablePort.SOCKET, 
null));
      }
   
      @Test
   diff --git 
a/geode-core/src/main/java/org/apache/geode/internal/AvailablePort.java 
b/geode-core/src/main/java/org/apache/geode/internal/AvailablePort.java
   index 4a1f33e5fe..6e764fa6b4 100644
   --- a/geode-core/src/main/java/org/apache/geode/internal/AvailablePort.java
   +++ b/geode-core/src/main/java/org/apache/geode/internal/AvailablePort.java
   @@ -14,9 +14,7 @@
     */
    package org.apache.geode.internal;
   
   -import java.io.IOException;
    import java.io.PrintStream;
   -import java.io.Serializable;
    import java.net.DatagramPacket;
    import java.net.Inet6Address;
    import java.net.InetAddress;
   @@ -78,7 +76,6 @@ public class AvailablePort {
       *
       * @param port The port to check
       * @param protocol The protocol to check (either {@link #SOCKET} or 
{@link #MULTICAST}).
   -   *
       * @throws IllegalArgumentException <code>protocol</code> is unknown
       */
      public static boolean isPortAvailable(final int port, int protocol) {
   @@ -92,7 +89,6 @@ public class AvailablePort {
       * @param port The port to check
       * @param protocol The protocol to check (either {@link #SOCKET} or 
{@link #MULTICAST}).
       * @param addr the bind address (or mcast address) to use
   -   *
       * @throws IllegalArgumentException <code>protocol</code> is unknown
       */
      public static boolean isPortAvailable(final int port, int protocol, 
InetAddress addr) {
   @@ -103,9 +99,7 @@ public class AvailablePort {
          } else {
            return testOneInterface(addr, port);
          }
   -    }
   -
   -    else if (protocol == MULTICAST) {
   +    } else if (protocol == MULTICAST) {
          MulticastSocket socket = null;
          try {
            socket = new MulticastSocket();
   @@ -161,46 +155,17 @@ public class AvailablePort {
        }
      }
   
   -  public static Keeper isPortKeepable(final int port, int protocol, 
InetAddress addr) {
   -    if (protocol == SOCKET) {
   -      // Try to create a ServerSocket
   -      if (addr == null) {
   -        return keepAllInterfaces(port);
   -      } else {
   -        return keepOneInterface(addr, port);
   -      }
   -    } else if (protocol == MULTICAST) {
   -      throw new IllegalArgumentException("You can not keep the JGROUPS 
protocol");
   -    } else {
   -      throw new IllegalArgumentException(String.format("Unknown protocol: 
%s",
   -          Integer.valueOf(protocol)));
   -    }
   -  }
   -
      private static boolean testOneInterface(InetAddress addr, int port) {
   -    Keeper k = keepOneInterface(addr, port);
   -    if (k != null) {
   -      k.release();
   -      return true;
   -    } else {
   -      return false;
   -    }
   -  }
   -
   -  private static Keeper keepOneInterface(InetAddress addr, int port) {
   -    ServerSocket server = null;
   +    ServerSocket socket = null;
        try {
   -      // (new Exception("Opening server socket on " + 
port)).printStackTrace();
   -      server = new ServerSocket();
   -      server.setReuseAddress(true);
   +      socket = new ServerSocket();
   +      socket.setReuseAddress(true);
          if (addr != null) {
   -        server.bind(new InetSocketAddress(addr, port));
   +        socket.bind(new InetSocketAddress(addr, port));
          } else {
   -        server.bind(new InetSocketAddress(port));
   +        socket.bind(new InetSocketAddress(port));
          }
   -      Keeper result = new Keeper(server, port);
   -      server = null;
   -      return result;
   +      return true;
        } catch (java.io.IOException ioe) {
          if (ioe.getMessage().equals("Network is unreachable")) {
            throw new RuntimeException("Network is unreachable");
   @@ -214,43 +179,33 @@ public class AvailablePort {
              // see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6558853
              // By returning true we ignore these interfaces and potentially 
say a
              // port is not in use when it really is.
   -          Keeper result = new Keeper(server, port);
   -          server = null;
   -          return result;
   +          return true;
            }
          }
   -      return null;
   +      return false;
        } catch (Exception ex) {
   -      return null;
   +      return false;
        } finally {
   -      if (server != null)
   +      if (socket != null) {
            try {
   -          server.close();
   +          socket.close();
            } catch (Exception ex) {
   
            }
   +      }
        }
      }
   
   +
      /**
       * Test to see if a given port is available port on all interfaces on 
this host.
       *
       * @return true of if the port is free on all interfaces
       */
      private static boolean testAllInterfaces(int port) {
   -    Keeper k = keepAllInterfaces(port);
   -    if (k != null) {
   -      k.release();
   -      return true;
   -    } else {
   -      return false;
   -    }
   -  }
   -
   -  private static Keeper keepAllInterfaces(int port) {
        // First check to see if we can bind to the wildcard address.
        if (!testOneInterface(null, port)) {
   -      return null;
   +      return false;
        }
   
        // Now check all of the addresses for all of the addresses
   @@ -275,59 +230,29 @@ public class AvailablePort {
            InetAddress addr = (InetAddress) en2.nextElement();
            boolean available = testOneInterface(addr, port);
            if (!available) {
   -          return null;
   +          return false;
            }
          }
        }
        // Now do it one more time but reserve the wildcard address
   -    return keepOneInterface(null, port);
   +    return testOneInterface(null, port);
      }
   
   -
      /**
       * Returns a randomly selected available port in the range 5001 to 32767.
       *
       * @param protocol The protocol to check (either {@link #SOCKET} or 
{@link #MULTICAST}).
   -   *
       * @throws IllegalArgumentException <code>protocol</code> is unknown
       */
      public static int getRandomAvailablePort(int protocol) {
        return getRandomAvailablePort(protocol, getAddress(protocol));
      }
   
   -  public static Keeper getRandomAvailablePortKeeper(int protocol) {
   -    return getRandomAvailablePortKeeper(protocol, getAddress(protocol));
   -  }
   -
   -  /**
   -   * Returns a randomly selected available port in the provided range.
   -   *
   -   * @param protocol The protocol to check (either {@link #SOCKET} or 
{@link #MULTICAST}).
   -   *
   -   * @throws IllegalArgumentException <code>protocol</code> is unknown
   -   */
   -  public static int getAvailablePortInRange(int rangeBase, int rangeTop, 
int protocol) {
   -    return getAvailablePortInRange(protocol, getAddress(protocol), 
rangeBase, rangeTop);
   -  }
   -
   -  /**
   -   * Returns a randomly selected available port in the range 5001 to 32767 
that satisfies a modulus
   -   *
   -   * @param protocol The protocol to check (either {@link #SOCKET} or 
{@link #MULTICAST}).
   -   *
   -   * @throws IllegalArgumentException <code>protocol</code> is unknown
   -   */
   -  public static int getRandomAvailablePortWithMod(int protocol, int mod) {
   -    return getRandomAvailablePortWithMod(protocol, getAddress(protocol), 
mod);
   -  }
   -
   -
      /**
       * Returns a randomly selected available port in the range 5001 to 32767.
       *
       * @param protocol The protocol to check (either {@link #SOCKET} or 
{@link #MULTICAST}).
       * @param addr the bind-address or mcast address to use
   -   *
       * @throws IllegalArgumentException <code>protocol</code> is unknown
       */
      public static int getRandomAvailablePort(int protocol, InetAddress addr) {
   @@ -340,7 +265,6 @@ public class AvailablePort {
       * @param protocol The protocol to check (either {@link #SOCKET} or 
{@link #MULTICAST}).
       * @param addr the bind-address or mcast address to use
       * @param useMembershipPortRange use true if the port will be used for 
membership
   -   *
       * @throws IllegalArgumentException <code>protocol</code> is unknown
       */
      public static int getRandomAvailablePort(int protocol, InetAddress addr,
   @@ -356,27 +280,11 @@ public class AvailablePort {
        }
      }
   
   -  public static Keeper getRandomAvailablePortKeeper(int protocol, 
InetAddress addr) {
   -    return getRandomAvailablePortKeeper(protocol, addr, false);
   -  }
   -
   -  public static Keeper getRandomAvailablePortKeeper(int protocol, 
InetAddress addr,
   -      boolean useMembershipPortRange) {
   -    while (true) {
   -      int port = getRandomWildcardBindPortNumber(useMembershipPortRange);
   -      Keeper result = isPortKeepable(port, protocol, addr);
   -      if (result != null) {
   -        return result;
   -      }
   -    }
   -  }
   -
      /**
       * Returns a randomly selected available port in the provided range.
       *
       * @param protocol The protocol to check (either {@link #SOCKET} or 
{@link #MULTICAST}).
       * @param addr the bind-address or mcast address to use
   -   *
       * @throws IllegalArgumentException <code>protocol</code> is unknown
       */
      public static int getAvailablePortInRange(int protocol, InetAddress addr, 
int rangeBase,
   @@ -395,7 +303,6 @@ public class AvailablePort {
       *
       * @param protocol The protocol to check (either {@link #SOCKET} or 
{@link #MULTICAST}).
       * @param addr the bind-address or mcast address to use
   -   *
       * @throws IllegalArgumentException <code>protocol</code> is unknown
       */
      public static int getRandomAvailablePortWithMod(int protocol, InetAddress 
addr, int mod) {
   @@ -413,10 +320,11 @@ public class AvailablePort {
   
      static {
        boolean fast = Boolean.getBoolean("AvailablePort.fastRandom");
   -    if (fast)
   +    if (fast) {
          rand = new Random();
   -    else
   +    } else {
          rand = new java.security.SecureRandom();
   +    }
      }
   
      private static int getRandomWildcardBindPortNumber() {
   @@ -448,7 +356,7 @@ public class AvailablePort {
        int numberOfRetrys = numberOfPorts * 5;
        for (int i = 0; i < numberOfRetrys; i++) {
          int port = rand.nextInt(numberOfPorts + 1) + rangeBase;// add 1 to 
numberOfPorts so that
   -                                                             // rangeTop 
also gets included
   +      // rangeTop also gets included
          if (isPortAvailable(port, protocol, getAddress(protocol))) {
            return port;
          }
   @@ -456,42 +364,6 @@ public class AvailablePort {
        return -1;
      }
   
   -  /**
   -   * This class will keep an allocated port allocated until it is used. 
This makes the window
   -   * smaller that can cause bug 46690
   -   *
   -   */
   -  public static class Keeper implements Serializable {
   -    private final transient ServerSocket ss;
   -    private final int port;
   -
   -    public Keeper(ServerSocket ss, int port) {
   -      this.ss = ss;
   -      this.port = port;
   -    }
   -
   -    public Keeper(ServerSocket ss, Integer port) {
   -      this.ss = ss;
   -      this.port = port != null ? port : 0;
   -    }
   -
   -    public int getPort() {
   -      return this.port;
   -    }
   -
   -    /**
   -     * Once you call this the socket will be freed and can then be 
reallocated by someone else.
   -     */
   -    public void release() {
   -      try {
   -        if (this.ss != null) {
   -          this.ss.close();
   -        }
   -      } catch (IOException ignore) {
   -      }
   -    }
   -  }
   -
      /////////////////////// Main Program ///////////////////////
   
      @Immutable
   @@ -504,7 +376,8 @@ public class AvailablePort {
        err.println("usage: java AvailablePort socket|jgroups [\"addr\" 
network-address] [port]");
        err.println("");
        err.println(
   -        "This program either prints whether or not a port is available for 
a given protocol, or it prints out an available port for a given protocol.");
   +        "This program either prints whether or not a port is available for 
a given protocol, or it "
   +            + "prints out an available port for a given protocol.");
        err.println("");
        ExitCode.FATAL.doSystemExit();
      }
   @@ -575,5 +448,4 @@ public class AvailablePort {
        }
   
      }
   -
    }
   diff --git 
a/geode-dunit/src/main/java/org/apache/geode/security/ClientAuthorizationTestCase.java
 
b/geode-dunit/src/main/java/org/apache/geode/security/ClientAuthorizationTestCase.java
   index 32d40d2c40..c7d9f10633 100644
   --- 
a/geode-dunit/src/main/java/org/apache/geode/security/ClientAuthorizationTestCase.java
   +++ 
b/geode-dunit/src/main/java/org/apache/geode/security/ClientAuthorizationTestCase.java
   @@ -72,7 +72,6 @@ import org.apache.geode.cache.query.SelectResults;
    import org.apache.geode.cache.query.Struct;
    import org.apache.geode.distributed.ConfigurationProperties;
    import org.apache.geode.distributed.internal.DistributionConfig;
   -import org.apache.geode.internal.AvailablePort.Keeper;
    import org.apache.geode.internal.AvailablePortHelper;
    import org.apache.geode.internal.cache.LocalRegion;
    import org.apache.geode.internal.cache.entries.AbstractRegionEntry;
   @@ -905,12 +904,9 @@ public abstract class ClientAuthorizationTestCase 
extends JUnit4DistributedTestC
            buildProperties(authenticator, accessor, false, extraAuthProps, 
extraAuthzProps);
   
        // Get ports for the servers
   -    List<Keeper> randomAvailableTCPPortKeepers =
   -        AvailablePortHelper.getRandomAvailableTCPPortKeepers(2);
   -    Keeper port1Keeper = randomAvailableTCPPortKeepers.get(0);
   -    Keeper port2Keeper = randomAvailableTCPPortKeepers.get(1);
   -    int port1 = port1Keeper.getPort();
   -    int port2 = port2Keeper.getPort();
   +    final int[] ports = AvailablePortHelper.getRandomAvailableTCPPorts(2);
   +    int port1 = ports[0];
   +    int port2 = ports[1];
   
        // Perform all the ops on the clients
        List opBlock = new ArrayList();
   @@ -925,7 +921,6 @@ public abstract class ClientAuthorizationTestCase 
extends JUnit4DistributedTestC
            // End of current operation block; execute all the operations on 
the servers with/without
            // failover
            if (opBlock.size() > 0) {
   -          port1Keeper.release();
   
              // Start the first server and execute the operation block
              server1.invoke("createCacheServer", () -> 
ClientAuthorizationTestCase
   @@ -937,7 +932,6 @@ public abstract class ClientAuthorizationTestCase 
extends JUnit4DistributedTestC
   
              if (!currentOp.equals(OperationWithAction.OPBLOCK_NO_FAILOVER)) {
                // Failover to the second server and run the block again
   -            port2Keeper.release();
   
                server2.invoke("createCacheServer", () -> 
ClientAuthorizationTestCase
                    .createCacheServer(port2, serverProps, javaProps));
   diff --git 
a/geode-dunit/src/main/java/org/apache/geode/test/dunit/internal/ChildVM.java 
b/geode-dunit/src/main/java/org/apache/geode/test/dunit/internal/ChildVM.java
   index ddd9a8ed10..1871cf6940 100644
   --- 
a/geode-dunit/src/main/java/org/apache/geode/test/dunit/internal/ChildVM.java
   +++ 
b/geode-dunit/src/main/java/org/apache/geode/test/dunit/internal/ChildVM.java
   @@ -18,7 +18,6 @@ import java.rmi.Naming;
   
    import org.apache.logging.log4j.Logger;
   
   -import org.apache.geode.internal.AvailablePortHelper;
    import org.apache.geode.internal.ExitCode;
    import org.apache.geode.logging.internal.OSProcess;
    import org.apache.geode.logging.internal.log4j.api.LogService;
   @@ -57,7 +56,6 @@ public class ChildVM {
          Naming.rebind(name, dunitVM);
          JUnit4DistributedTestCase.initializeBlackboard();
          holder.signalVMReady();
   -      AvailablePortHelper.initializeUniquePortRange(vmNum + 2); // hacky, 
locator is -2
          // This loop is here so this VM will die even if the master is mean 
killed.
          while (!stopMainLoop) {
            holder.ping();
   diff --git 
a/geode-dunit/src/main/java/org/apache/geode/test/dunit/rules/ClusterStartupRule.java
 
b/geode-dunit/src/main/java/org/apache/geode/test/dunit/rules/ClusterStartupRule.java
   index c817f8c654..cffd43c7fd 100644
   --- 
a/geode-dunit/src/main/java/org/apache/geode/test/dunit/rules/ClusterStartupRule.java
   +++ 
b/geode-dunit/src/main/java/org/apache/geode/test/dunit/rules/ClusterStartupRule.java
   @@ -29,6 +29,7 @@ import java.util.Map;
    import java.util.Properties;
    import java.util.stream.Collectors;
   
   +import com.google.common.io.Files;
    import org.apache.commons.io.FileUtils;
    import org.apache.commons.lang3.JavaVersion;
    import org.junit.runner.Description;
   @@ -173,8 +174,11 @@ public class ClusterStartupRule implements 
SerializableTestRule {
        vms.forEach(x -> x.stop());
   
        // delete any file under root dir
   -    Arrays.stream(getWorkingDirRoot().listFiles()).filter(File::isFile)
   -        .forEach(FileUtils::deleteQuietly);
   +    final File[] files = getWorkingDirRoot().listFiles();
   +    if (null != files) {
   +      Arrays.stream(files).filter(File::isFile)
   +          .forEach(FileUtils::deleteQuietly);
   +    }
   
        restoreSystemProperties.afterDistributedTest(description);
   
   @@ -362,9 +366,11 @@ public class ClusterStartupRule implements 
SerializableTestRule {
        member.getVM().bounceForcibly();
      }
   
   +  private static final File baseDir = Files.createTempDir();
   +
      public File getWorkingDirRoot() {
        // return the dunit folder
   -    return new File(DUnitLauncher.DUNIT_DIR);
   +    return new File(baseDir, DUnitLauncher.DUNIT_DIR);
      }
   
      public static void stopElementInsideVM() {
   diff --git 
a/geode-dunit/src/main/java/org/apache/geode/test/junit/rules/MemberStarterRule.java
 
b/geode-dunit/src/main/java/org/apache/geode/test/junit/rules/MemberStarterRule.java
   index ff0d7f2c1b..17c74ce3a7 100644
   --- 
a/geode-dunit/src/main/java/org/apache/geode/test/junit/rules/MemberStarterRule.java
   +++ 
b/geode-dunit/src/main/java/org/apache/geode/test/junit/rules/MemberStarterRule.java
   @@ -14,6 +14,7 @@
     */
    package org.apache.geode.test.junit.rules;
   
   +import static java.lang.String.valueOf;
    import static 
org.apache.geode.distributed.ConfigurationProperties.HTTP_SERVICE_BIND_ADDRESS;
    import static 
org.apache.geode.distributed.ConfigurationProperties.HTTP_SERVICE_PORT;
    import static 
org.apache.geode.distributed.ConfigurationProperties.JMX_MANAGER;
   @@ -279,8 +280,7 @@ public abstract class MemberStarterRule<T> extends 
SerializableExternalResource
      public T withJMXManager(boolean useProductDefaultPorts) {
        if (!useProductDefaultPorts) {
          // do no override these properties if already exists
   -      properties.putIfAbsent(JMX_MANAGER_PORT,
   -          portSupplier.getAvailablePort() + "");
   +      properties.putIfAbsent(JMX_MANAGER_PORT, 
valueOf(portSupplier.getAvailablePort()));
          this.jmxPort = 
Integer.parseInt(properties.getProperty(JMX_MANAGER_PORT));
        } else {
          // the real port numbers will be set after we started the 
server/locator.
   @@ -294,8 +294,7 @@ public abstract class MemberStarterRule<T> extends 
SerializableExternalResource
      public T withHttpService(boolean useDefaultPort) {
        properties.setProperty(HTTP_SERVICE_BIND_ADDRESS, "localhost");
        if (!useDefaultPort) {
   -      properties.put(HTTP_SERVICE_PORT,
   -          portSupplier.getAvailablePort() + "");
   +      properties.put(HTTP_SERVICE_PORT, 
valueOf(portSupplier.getAvailablePort()));
          this.httpPort = 
Integer.parseInt(properties.getProperty(HTTP_SERVICE_PORT));
        } else {
          // indicate start http service but with default port
   @@ -462,7 +461,7 @@ public abstract class MemberStarterRule<T> extends 
SerializableExternalResource
      public CacheServerMXBean getCacheServerMXBean(String serverName, int 
serverPort) {
        SystemManagementService managementService = (SystemManagementService) 
getManagementService();
        String objectName = 
MessageFormat.format(OBJECTNAME__CLIENTSERVICE_MXBEAN,
   -        String.valueOf(serverPort), serverName);
   +        valueOf(serverPort), serverName);
        ObjectName cacheServerMBeanName = 
MBeanJMXAdapter.getObjectName(objectName);
        return managementService.getMBeanProxy(cacheServerMBeanName, 
CacheServerMXBean.class);
      }
   @@ -541,7 +540,7 @@ public abstract class MemberStarterRule<T> extends 
SerializableExternalResource
          // There is a very slight race condition here, where the above could 
conceivably time out,
          // and become satisfied before the next supplier.get()
          throw new ConditionTimeoutException(
   -          "The observed result '" + String.valueOf(supplier.get())
   +          "The observed result '" + valueOf(supplier.get())
                  + "' does not satisfy the provided assertionConsumer. \n" + 
e.getMessage());
        }
      }
   diff --git 
a/geode-junit/src/main/java/org/apache/geode/internal/AvailablePortHelper.java 
b/geode-junit/src/main/java/org/apache/geode/internal/AvailablePortHelper.java
   index 643a5bdcac..e9bd97189b 100644
   --- 
a/geode-junit/src/main/java/org/apache/geode/internal/AvailablePortHelper.java
   +++ 
b/geode-junit/src/main/java/org/apache/geode/internal/AvailablePortHelper.java
   @@ -14,17 +14,13 @@
     */
    package org.apache.geode.internal;
   
   -import static 
org.apache.geode.distributed.internal.DistributionConfig.DEFAULT_MEMBERSHIP_PORT_RANGE;
   -import static 
org.apache.geode.internal.AvailablePort.AVAILABLE_PORTS_LOWER_BOUND;
   -import static 
org.apache.geode.internal.AvailablePort.AVAILABLE_PORTS_UPPER_BOUND;
   -import static org.apache.geode.internal.AvailablePort.getAddress;
   
   -import java.util.ArrayList;
   -import java.util.List;
   -import java.util.Random;
   -import java.util.concurrent.atomic.AtomicInteger;
   +import java.io.IOException;
   +import java.net.DatagramSocket;
   +import java.net.InetSocketAddress;
   +import java.net.ServerSocket;
   +import java.net.SocketException;
   
   -import org.apache.geode.internal.AvailablePort.Keeper;
   
    /**
     * Provides helper methods for acquiring a set of unique available ports. 
It is not safe to simply
   @@ -33,124 +29,32 @@ import org.apache.geode.internal.AvailablePort.Keeper;
     * getRandomAvailablePort to return the same integer, unless that port is 
put into use before
     * further calls to getRandomAvailablePort.
     */
   -public class AvailablePortHelper {
   -  private final AtomicInteger currentMembershipPort;
   -  private final AtomicInteger currentAvailablePort;
   -
   -  // Singleton object is only used to track the current ports
   -  private static final AvailablePortHelper singleton = new 
AvailablePortHelper();
   -
   -  AvailablePortHelper() {
   -    Random rand;
   -    boolean fast = Boolean.getBoolean("AvailablePort.fastRandom");
   -    if (fast)
   -      rand = new Random();
   -    else
   -      rand = new java.security.SecureRandom();
   -    currentMembershipPort = new AtomicInteger(
   -        rand.nextInt(DEFAULT_MEMBERSHIP_PORT_RANGE[1] - 
DEFAULT_MEMBERSHIP_PORT_RANGE[0])
   -            + DEFAULT_MEMBERSHIP_PORT_RANGE[0]);
   -    currentAvailablePort =
   -        new AtomicInteger(rand.nextInt(AVAILABLE_PORTS_UPPER_BOUND - 
AVAILABLE_PORTS_LOWER_BOUND)
   -            + AVAILABLE_PORTS_LOWER_BOUND);
   -  }
   +public abstract class AvailablePortHelper {
   
      /**
       * Returns array of unique randomly available tcp ports of specified 
count.
       */
      public static int[] getRandomAvailableTCPPorts(int count) {
   -    return getRandomAvailableTCPPorts(count, false);
   +    return getRandomAvailableTCPPortRange(count);
      }
   
      /**
       * Returns an array of unique randomly available tcp ports
       *
       * @param count number of desired ports
   -   * @param useMembershipPortRange whether to use the configured 
membership-port-range
       * @return the ports
       */
   -  public static int[] getRandomAvailableTCPPorts(int count, boolean 
useMembershipPortRange) {
   -    List<Keeper> list = getRandomAvailableTCPPortKeepers(count, 
useMembershipPortRange);
   -    int[] ports = new int[list.size()];
   -    int i = 0;
   -    for (Keeper k : list) {
   -      ports[i] = k.getPort();
   -      k.release();
   -      i++;
   -    }
   -    return ports;
   -  }
   -
   -  public static List<Keeper> getRandomAvailableTCPPortKeepers(int count) {
   -    return getRandomAvailableTCPPortKeepers(count, false);
   -  }
   -
   -  private static List<Keeper> getRandomAvailableTCPPortKeepers(int count,
   -      boolean useMembershipPortRange) {
   -    List<Keeper> result = new ArrayList<>();
   -    while (result.size() < count) {
   -      result.add(getUniquePortKeeper(useMembershipPortRange, 
AvailablePort.SOCKET));
   -    }
   -    return result;
   -  }
   -
      public static int[] getRandomAvailableTCPPortRange(final int count) {
   -    return getRandomAvailableTCPPortRange(count, false);
   -  }
   -
   -  public static int[] getRandomAvailableTCPPortRange(final int count,
   -      final boolean useMembershipPortRange) {
   -    List<Keeper> list =
   -        getUniquePortRangeKeepers(useMembershipPortRange, 
AvailablePort.SOCKET,
   -            count);
   -    int[] ports = new int[list.size()];
   -    int i = 0;
   -    for (Keeper k : list) {
   -      ports[i] = k.getPort();
   -      k.release();
   -      i++;
   -    }
   -    return ports;
   -  }
   -
   -  public static List<Keeper> getRandomAvailableTCPPortRangeKeepers(final 
int count) {
   -    return getRandomAvailableTCPPortRangeKeepers(count, false);
   -  }
   -
   -  public static List<Keeper> getRandomAvailableTCPPortRangeKeepers(final 
int count,
   -      final boolean useMembershipPortRange) {
   -    return getUniquePortRangeKeepers(useMembershipPortRange, 
AvailablePort.SOCKET,
   -        count);
   -  }
   -
   -  private static void releaseKeepers(List<Keeper> keepers) {
   -    for (Keeper keeper : keepers) {
   -      keeper.release();
   -    }
   +    return getRandomAvailableTCPPortsForDUnitSite(count);
      }
   
      /**
       * Returns array of unique randomly available tcp ports of specified 
count.
       */
   -  public static int[] getRandomAvailableTCPPortsForDUnitSite(int count) {
   -    int site = 1;
   -    String hostName = System.getProperty("hostName");
   -    if (hostName != null && hostName.startsWith("host") && 
hostName.length() > 4) {
   -      site = Integer.parseInt(hostName.substring(4));
   -    }
   -
   +  public static int[] getRandomAvailableTCPPortsForDUnitSite(final int 
count) {
        int[] ports = new int[count];
   -    int i = 0;
   -    while (i < count) {
   -      int port = getUniquePort(false, AvailablePort.SOCKET);
   -      // This logic is from AvailablePort.getRandomAvailablePortWithMod 
which this method used to
   -      // call. It seems like the check should be (port % FOO == site) for 
some FOO, but given how
   -      // widely this is used, it's not at all clear that no one's depending 
on the current behavior.
   -      while (port % site != 0) {
   -        port = getUniquePort(false, AvailablePort.SOCKET);
   -      }
   -      ports[i] = port;
   -      ++i;
   +    for (int i = 0; i < count; ++i) {
   +      ports[i] = getRandomAvailablePortForDUnitSite();
        }
        return ports;
      }
   @@ -160,131 +64,40 @@ public class AvailablePortHelper {
       * Returns array of unique randomly available tcp ports of specified 
count.
       */
      public static int getRandomAvailablePortForDUnitSite() {
   -    return getRandomAvailableTCPPortsForDUnitSite(1)[0];
   +    return getRandomAvailableTCPPort();
      }
   
   -
      /**
   -   * Returns randomly available tcp port.
   +   * Returns available ephemeral TCP port.
       */
      public static int getRandomAvailableTCPPort() {
   -    return getRandomAvailableTCPPorts(1)[0];
   -  }
   -
   -  /**
   -   * Returns array of unique randomly available udp ports of specified 
count.
   -   */
   -  private static int[] getRandomAvailableUDPPorts(int count) {
   -    int[] ports = new int[count];
   -    int i = 0;
   -    while (i < count) {
   -      ports[i] = getUniquePort(false, AvailablePort.MULTICAST);
   -      ++i;
   +    try (final ServerSocket socket = bindEphemeralTcpSocket()) {
   +      return socket.getLocalPort();
   +    } catch (IOException e) {
   +      throw new IllegalStateException(e);
        }
   -    return ports;
      }
   
      /**
   -   * Returns randomly available udp port.
   +   * Returns available ephemeral UDP port.
       */
      public static int getRandomAvailableUDPPort() {
   -    return getRandomAvailableUDPPorts(1)[0];
   -  }
   -
   -  public static void initializeUniquePortRange(int rangeNumber) {
   -    if (rangeNumber < 0) {
   -      throw new RuntimeException("Range number cannot be negative.");
   -    }
   -    singleton.currentMembershipPort.set(DEFAULT_MEMBERSHIP_PORT_RANGE[0]);
   -    singleton.currentAvailablePort.set(AVAILABLE_PORTS_LOWER_BOUND);
   -    if (rangeNumber != 0) {
   -      // This code will generate starting points such that range 0 starts 
at the lowest possible
   -      // value, range 1 starts halfway through the total available ports, 2 
starts 1/4 of the way
   -      // through, then further ranges are 3/4, 1/8, 3/8, 5/8, 7/8, 1/16, 
etc.
   -
   -      // This spaces the ranges out as much as possible for low numbers of 
ranges, while also making
   -      // it possible to grow the number of ranges without bound (within 
some reasonable fraction of
   -      // the number of available ports)
   -      int membershipRange = DEFAULT_MEMBERSHIP_PORT_RANGE[1] - 
DEFAULT_MEMBERSHIP_PORT_RANGE[0];
   -      int availableRange = AVAILABLE_PORTS_UPPER_BOUND - 
AVAILABLE_PORTS_LOWER_BOUND;
   -      int numChunks = Integer.highestOneBit(rangeNumber) << 1;
   -      int chunkNumber = 2 * (rangeNumber - 
Integer.highestOneBit(rangeNumber)) + 1;
   -
   -      singleton.currentMembershipPort.addAndGet(chunkNumber * 
membershipRange / numChunks);
   -      singleton.currentAvailablePort.addAndGet(chunkNumber * availableRange 
/ numChunks);
   +    try (final DatagramSocket socket = bindEphemeralUdpSocket()) {
   +      return socket.getLocalPort();
   +    } catch (SocketException e) {
   +      throw new IllegalStateException(e);
        }
      }
   
   -  /**
   -   * Get keeper objects for the next unused, consecutive 'rangeSize' ports 
on this machine.
   -   *
   -   * @param useMembershipPortRange - if true, select ports from the
   -   *        DistributionConfig.DEFAULT_MEMBERSHIP_PORT_RANGE
   -   * @param protocol - either AvailablePort.SOCKET (TCP) or 
AvailablePort.MULTICAST (UDP)
   -   * @param rangeSize - number of contiguous ports needed
   -   * @return Keeper objects associated with a range of ports satisfying the 
request
   -   */
   -  private static List<Keeper> getUniquePortRangeKeepers(boolean 
useMembershipPortRange,
   -      int protocol, int rangeSize) {
   -    AtomicInteger targetRange =
   -        useMembershipPortRange ? singleton.currentMembershipPort : 
singleton.currentAvailablePort;
   -    int targetBound =
   -        useMembershipPortRange ? DEFAULT_MEMBERSHIP_PORT_RANGE[1] : 
AVAILABLE_PORTS_UPPER_BOUND;
   -
   -    while (true) {
   -      int uniquePort = targetRange.getAndAdd(rangeSize);
   -      if (uniquePort + rangeSize > targetBound) {
   -        targetRange.set(useMembershipPortRange ? 
DEFAULT_MEMBERSHIP_PORT_RANGE[0]
   -            : AVAILABLE_PORTS_LOWER_BOUND);
   -        continue;
   -      }
   -      List<Keeper> keepers = new ArrayList<>();
   -      int validPortsFound = 0;
   -
   -      while (validPortsFound < rangeSize) {
   -        Keeper testKeeper =
   -            AvailablePort.isPortKeepable(uniquePort++, protocol,
   -                getAddress(protocol));
   -        if (testKeeper == null) {
   -          break;
   -        }
   -
   -        keepers.add(testKeeper);
   -        ++validPortsFound;
   -      }
   -
   -      if (validPortsFound == rangeSize) {
   -        return keepers;
   -      }
   -
   -      releaseKeepers(keepers);
   -    }
   +  private static DatagramSocket bindEphemeralUdpSocket() throws 
SocketException {
   +    return new DatagramSocket();
      }
   
   -  private static Keeper getUniquePortKeeper(boolean useMembershipPortRange, 
int protocol) {
   -    return getUniquePortRangeKeepers(useMembershipPortRange, protocol, 
1).get(0);
   +  private static ServerSocket bindEphemeralTcpSocket() throws IOException {
   +    ServerSocket socket = new ServerSocket();
   +    socket.bind(new InetSocketAddress(0));
   +    return socket;
      }
   
   -  /**
   -   * Get the next available port on this machine.
   -   */
   -  private static int getUniquePort(boolean useMembershipPortRange, int 
protocol) {
   -    AtomicInteger targetRange =
   -        useMembershipPortRange ? singleton.currentMembershipPort : 
singleton.currentAvailablePort;
   -    int targetBound =
   -        useMembershipPortRange ? DEFAULT_MEMBERSHIP_PORT_RANGE[1] : 
AVAILABLE_PORTS_UPPER_BOUND;
   -
   -    while (true) {
   -      int uniquePort = targetRange.getAndIncrement();
   -      if (uniquePort > targetBound) {
   -        targetRange.set(useMembershipPortRange ? 
DEFAULT_MEMBERSHIP_PORT_RANGE[0]
   -            : AVAILABLE_PORTS_LOWER_BOUND);
   -        continue;
   -      }
   
   -      if (AvailablePort.isPortAvailable(uniquePort, protocol, 
getAddress(protocol))) {
   -        return uniquePort;
   -      }
   -    }
   -  }
    }
   diff --git 
a/geode-junit/src/main/java/org/apache/geode/internal/UniquePortSupplier.java 
b/geode-junit/src/main/java/org/apache/geode/internal/UniquePortSupplier.java
   index af75da95c8..69918445fc 100644
   --- 
a/geode-junit/src/main/java/org/apache/geode/internal/UniquePortSupplier.java
   +++ 
b/geode-junit/src/main/java/org/apache/geode/internal/UniquePortSupplier.java
   @@ -14,34 +14,13 @@
     */
    package org.apache.geode.internal;
   
   -import java.util.HashSet;
   -import java.util.Set;
   -import java.util.function.IntSupplier;
   -import java.util.stream.IntStream;
   
    /**
     * Supplies unique ports that have not already been supplied by this 
instance of PortSupplier
     */
    public class UniquePortSupplier {
   
   -  private final IntSupplier supplier;
   -  private final Set<Integer> usedPorts = new HashSet<>();
   -
   -  public UniquePortSupplier() {
   -    supplier = () -> AvailablePortHelper.getRandomAvailableTCPPort();
   -  }
   -
   -  public UniquePortSupplier(IntSupplier supplier) {
   -    this.supplier = supplier;
   -  }
   -
   -  public synchronized int getAvailablePort() {
   -    int result = IntStream.generate(supplier)
   -        .filter(port -> !usedPorts.contains(port))
   -        .findFirst()
   -        .getAsInt();
   -
   -    usedPorts.add(result);
   -    return result;
   +  public int getAvailablePort() {
   +    return AvailablePortHelper.getRandomAvailableTCPPort();
      }
    }
   diff --git 
a/geode-junit/src/test/java/org/apache/geode/internal/UniquePortSupplierTest.java
 
b/geode-junit/src/test/java/org/apache/geode/internal/UniquePortSupplierTest.java
   deleted file mode 100644
   index 06904260b6..0000000000
   --- 
a/geode-junit/src/test/java/org/apache/geode/internal/UniquePortSupplierTest.java
   +++ /dev/null
   @@ -1,48 +0,0 @@
   -/*
   - * Licensed to the Apache Software Foundation (ASF) under one or more 
contributor license
   - * agreements. See the NOTICE file distributed with this work for 
additional information regarding
   - * copyright ownership. The ASF licenses this file to You under the Apache 
License, Version 2.0 (the
   - * "License"); you may not use this file except in compliance with the 
License. You may obtain a
   - * copy of the License at
   - *
   - * http://www.apache.org/licenses/LICENSE-2.0
   - *
   - * Unless required by applicable law or agreed to in writing, software 
distributed under the License
   - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 
ANY KIND, either express
   - * or implied. See the License for the specific language governing 
permissions and limitations under
   - * the License.
   - */
   -package org.apache.geode.internal;
   -
   -import static org.assertj.core.api.Assertions.assertThat;
   -
   -import java.util.PrimitiveIterator;
   -import java.util.stream.IntStream;
   -
   -import org.junit.Test;
   -
   -public class UniquePortSupplierTest {
   -
   -  @Test
   -  public void returnsUniquePorts() {
   -    // Create a stream that returns the same number more than once, make 
sure we find
   -    // a unique port
   -    PrimitiveIterator.OfInt iterator = IntStream.of(0, 0, 0, 0, 0, 
1).iterator();
   -    UniquePortSupplier supplier = new UniquePortSupplier(iterator::nextInt);
   -    int port0 = supplier.getAvailablePort();
   -    int port1 = supplier.getAvailablePort();
   -
   -    assertThat(port0).isEqualTo(0);
   -    assertThat(port1).isEqualTo(1);
   -  }
   -
   -  @Test
   -  public void getsPortsFromProvidedSupplier() {
   -    int expectedPort = 555;
   -
   -    UniquePortSupplier supplier = new UniquePortSupplier(() -> 
expectedPort);
   -    int port = supplier.getAvailablePort();
   -
   -    assertThat(port).isEqualTo(expectedPort);
   -  }
   -}
   
   Inline redundant AvailablePortHelper methods
   
   Authored-by: Dale Emery <dem...@vmware.com>
   
   DistributedSystemDUnitTest reserves port sequence
   
   Authored-by: Dale Emery <dem...@vmware.com>
   
   Remove AvailablePort.Keeper from excluded classes
   
   Authored-by: Dale Emery <dem...@vmware.com>
   
   Remove inadvertently added ClusterStartupRule changes
   
   Authored-by: Dale Emery <dem...@vmware.com>
   
   Thank you for submitting a contribution to Apache Geode.
   
   In order to streamline the review of the contribution we ask you
   to ensure the following steps have been taken:
   
   ### For all changes:
   - [ ] Is there a JIRA ticket associated with this PR? Is it referenced in 
the commit message?
   
   - [ ] Has your PR been rebased against the latest commit within the target 
branch (typically `develop`)?
   
   - [ ] Is your initial contribution a single, squashed commit?
   
   - [ ] Does `gradlew build` run cleanly?
   
   - [ ] Have you written or updated unit tests to verify your changes?
   
   - [ ] If adding new dependencies to the code, are these dependencies 
licensed in a way that is compatible for inclusion under [ASF 
2.0](http://www.apache.org/legal/resolved.html#category-a)?
   
   ### Note:
   Please ensure that once the PR is submitted, check Concourse for build 
issues and
   submit an update to your PR as soon as possible. If you need help, please 
send an
   email to d...@geode.apache.org.
   


----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


Reply via email to