PortUtil fixes from my working branch to avoid test failures

This commit is contained in:
James Agnew 2019-04-15 10:34:27 -04:00
parent 0848fdf1eb
commit cff79e6aef
2 changed files with 24 additions and 22 deletions

View File

@ -217,28 +217,20 @@ public class PortUtil {
}
private static boolean isAvailable(int port) {
ServerSocket ss = null;
DatagramSocket ds = null;
try {
ss = new ServerSocket(port);
ourLog.info("Testing a bind on port {}", port);
try (ServerSocket ss = new ServerSocket(port)) {
ss.setReuseAddress(true);
ds = new DatagramSocket(port);
try (DatagramSocket ds = new DatagramSocket(port)) {
ds.setReuseAddress(true);
ourLog.info("Successfully bound port {}", port);
return true;
} catch (IOException e) {
ourLog.info("Failed to bind port {}: {}", port, e.toString());
return false;
} finally {
if (ds != null) {
ds.close();
}
if (ss != null) {
try {
ss.close();
} catch (IOException e) {
/* should not be thrown */
}
}
ourLog.info("Failed to bind port {}: {}", port, e.toString());
return false;
}
}

View File

@ -63,13 +63,23 @@ public class PortUtilTest {
for (int j = 0; j < portsPerTaskCount; j++) {
int nextFreePort = portUtil.getNextFreePort();
boolean bound;
try (ServerSocket ss = new ServerSocket()) {
ss.bind(new InetSocketAddress("localhost", nextFreePort));
bound = true;
} catch (IOException e) {
String msg = "Failure binding new port " + nextFreePort + ": " + e.toString();
bound = false;
}
if (!bound) {
try (ServerSocket ss = new ServerSocket()) {
Thread.sleep(1000);
ss.bind(new InetSocketAddress("localhost", nextFreePort));
} catch (Exception e) {
String msg = "Failure binding new port (second attempt) " + nextFreePort + ": " + e.toString();
ourLog.error(msg, e);
errors.add(msg);
}
}
ports.add(nextFreePort);