JAVA-8748: Use ServerSocket(0) approach to get free port

This commit is contained in:
Krzysiek 2021-12-02 12:58:13 +01:00
parent 9d0dd5e34f
commit 85faed7f39
1 changed files with 4 additions and 14 deletions

View File

@ -9,7 +9,6 @@ import org.springframework.util.SocketUtils;
import java.io.IOException; import java.io.IOException;
import java.net.ServerSocket; import java.net.ServerSocket;
import java.util.Random;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail; import static org.assertj.core.api.Assertions.fail;
@ -148,19 +147,10 @@ public class FindFreePortUnitTest {
} }
private int getFreePort() { private int getFreePort() {
return new Random() try(ServerSocket serverSocket = new ServerSocket(0)){
.ints(36000, 65000) return serverSocket.getLocalPort();
.filter(FindFreePortUnitTest::isFree) } catch (IOException ex){
.findFirst() return DEFAULT_RANDOM_PORT;
.orElse(DEFAULT_RANDOM_PORT);
}
private static boolean isFree(int port) {
try {
new ServerSocket(port).close();
return true;
} catch (IOException e) {
return false;
} }
} }
} }