Skip to content

Commit

Permalink
trying picking ports at random instead of in ascending order
Browse files Browse the repository at this point in the history
  • Loading branch information
lassewesth committed Jun 29, 2017
1 parent 00e2a2d commit b2e2258
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 39 deletions.
Expand Up @@ -51,36 +51,6 @@ public boolean isOccupied( int port )
return true; return true;
} }


// // poke at the port and as a side-effect, waste some time
// try ( Socket ignored = new Socket( "0.0.0.0", port ) )
// {
//
// }
// catch ( IOException e )
// {
// return true;
// }
//
// // poke at the port and as a side-effect, waste some time
// try ( Socket ignored = new Socket( InetAddress.getLoopbackAddress(), port ) )
// {
//
// }
// catch ( IOException e )
// {
// return true;
// }
// or not because that ate all ports very quickly...

try
{
Thread.sleep( 2000 );
}
catch ( InterruptedException e )
{
// best effort
}

return false; return false;
} }
} }
Expand Up @@ -26,26 +26,30 @@
import java.nio.file.FileAlreadyExistsException; import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.Random;


public class PortRepository public class PortRepository
{ {
private final Path directory; private static final Random RANDOM = new Random();


private int currentPort; private final Path directory;
private final int lowestPort;


public PortRepository( Path directory, int initialPort ) public PortRepository( Path directory, int lowestPort )
{ {
this.directory = directory; this.directory = directory;

this.lowestPort = lowestPort;
this.currentPort = initialPort;
} }


// synchronize between threads in this JVM // synchronize between threads in this JVM
public synchronized int reserveNextPort( String trace ) public synchronized int reserveNextPort( String trace )
{ {
while ( currentPort <= EphemeralPortMaximum ) // if we do not find one after trying 100 times, bail out
for ( int i = 0; i < 100; i++ )
{ {
Path portFilePath = directory.resolve( "port" + currentPort ); int port = lowestPort + RANDOM.nextInt( PortConstants.EphemeralPortMaximum - lowestPort );

Path portFilePath = directory.resolve( "port" + port );


try try
{ {
Expand All @@ -57,11 +61,11 @@ public synchronized int reserveNextPort( String trace )
fileOutputStream.flush(); fileOutputStream.flush();
} }


return currentPort++; return port;
} }
catch ( FileAlreadyExistsException e ) catch ( FileAlreadyExistsException e )
{ {
currentPort++; // try again
} }
catch ( IOException e ) catch ( IOException e )
{ {
Expand Down

0 comments on commit b2e2258

Please sign in to comment.