@ VisibleForTesting static int getNextAvailablePort ( InetAddress address , PortAllocator portAllocator ) { for ( int i = 0 ; i < PORT_MAX_TRIES ; i ++ ) { int port = portAllocator . getAvailable ( address ) ; if ( isValidPort ( port ) ) { PORTS_ALREADY_ALLOCATED . add ( port ) ; return port ; } } throw new IllegalStateException ( "Fail to find an available port on " + address ) ; }
Warning - the allocated ports are kept in memory and are never clean - up . Besides the memory consumption that means that ports already allocated are never freed . As a consequence no more than ~64512 calls to this method are allowed .