Here you can find the source of findFreePort()
public static synchronized int findFreePort() throws IOException
//package com.java2s; //License from project: Apache License import java.io.IOException; import java.net.ServerSocket; public class Main { public static synchronized int findFreePort() throws IOException { try (ServerSocket socket = new ServerSocket(0)) { return socket.getLocalPort(); }/*from ww w .j av a 2 s. c o m*/ } }