Revisions for untitled paste

View the changes made to this paste.

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

2.java

@@ -0,0 +1,15 @@

+    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;
+        }
+    }
\ No newline at end of file

1.java

@@ -0,0 +1,16 @@

+    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);
+            }
+        }
+    }
\ No newline at end of file