SocketAnalyzer { public static Boolean awaitPortAvailable(final int port, final long timeout, final TimeUnit timeUnit) throws InterruptedException { final long expectedEndTime = System.nanoTime() + timeUnit.toNanos(timeout); while (System.nanoTime() <= expectedEndTime) { LOG.debug("Check if port {} is available", port); try (ServerSocket serverSocket = new ServerSocket(port)) { LOG.debug("Port {} available", port); return true; } catch (IOException e) { LOG.info("Port {} is not available - Awaiting port availability 1s", port); Thread.sleep(SOCKET_PORT_WAIT_TIME); } } return false; } private  SocketAnalyzer(); static Boolean awaitPortAvailable(final int port, final long timeout, final TimeUnit timeUnit);  }
@Test public void socketAnalyzerAwaitPortSuccess() throws IOException { ServerSocket blockingSocket = null; try { final int availablePort = findAvailablePort(); blockingSocket = new ServerSocket(availablePort); Assert.assertFalse(SocketAnalyzer.awaitPortAvailable(availablePort, TIMEOUT, TimeUnit.SECONDS)); } catch (InterruptedException | IOException e) { Assert.fail("SocketAnalyzer test failed.", e); } finally { if (blockingSocket != null) { blockingSocket.close(); } } }