⁨bendem⁩ avatar
bendem

untitled paste

unlisted ⁨2⁩ ⁨files⁩ 2019-03-25 10:13:31 UTC

1.java

Raw
    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

Raw
    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;
        }
    }