code: public static int availablePort() {
      ServerSocket serverSocket = null;
  
      try {
        serverSocket = new ServerSocket(0);
        return serverSocket.getLocalPort();
      }
      catch (IOException cause) {
        throw new NoAvailablePortException("No port available", cause);
      }
      finally {
        close(serverSocket);
      }
    }
docs: Gets an available network port used by a network service on which to listen for client {@link Socket} connections.
  
  @return in integer value indicating an available network port.