Here you can find the source of getAvailablePort(int startPort)
public static synchronized int getAvailablePort(int startPort)
//package com.java2s; /*// w ww. j a v a 2 s. c o m * * Copyright 2013 LinkedIn Corp. All rights reserved * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ import java.io.IOException; import java.net.DatagramSocket; import java.net.ServerSocket; import java.util.HashSet; import java.util.Set; public class Main { /** * The set of ports assigned by {@link #getAvailablePort(int)}. This is to avoid race conditions * by different tests using the same port. */ private static final Set<Integer> _assignedPorts = new HashSet<Integer>(); /** * Find the first available port after a given port * @return an available port **/ public static synchronized int getAvailablePort(int startPort) { int port = startPort; while (_assignedPorts.contains(port) && !portAvailable(port) && port < 0x7FFFFFFF) { port++; } if (0x7FFFFFFF == port) { throw new RuntimeException("no available port found starting at " + startPort); } _assignedPorts.add(port); return port; } /** * Checks to see if a specific port is available. * * @param port the port to check for availability */ public static boolean portAvailable(int port) { if (port < 1200 || port > 65000) { throw new IllegalArgumentException("Invalid start port: " + port); } ServerSocket ss = null; DatagramSocket ds = null; try { ss = new ServerSocket(port); ss.setReuseAddress(true); ds = new DatagramSocket(port); ds.setReuseAddress(true); return true; } catch (IOException e) { } finally { if (ds != null) { ds.close(); } if (ss != null) { try { ss.close(); } catch (IOException e) { /* should not be thrown */ } } } return false; } }