1.java
public static int findFreePort() {
ServerSocket socket = null;
try {
socket = new ServerSocket(0);
socket.setReuseAddress(true);
int port = socket.getLocalPort();
closeQuietly(socket);
return port;
} catch (IOException e) {
throw new UncheckedIoException(e);
} finally {
if (socket != null) {
closeQuietly(socket);
}
}
}
2.java
public static int findFreePort() {
int portUsed;
do {
portUsed = PORT.getAndIncrement();
} while (!available(portUsed));
return portUsed;
}
private static boolean available(int port) {
try (Socket ignored = new Socket("localhost", port)) {
return false;
} catch (IOException ignored) {
return true;
}
}