private int lookupForward(int min, int max) { for (int port = min; port <= max; port++) { if (checkPort(port)) { return port; } } return -1; }
/** * Get free port from the whole range of possible ports. * * @return free port or {@code -1} if there is no free port */ public int acquire() { return doAcquire(range.first, range.second); }
private int doAcquire(int min, int max) { // Use this for getting ports for web applications but unfortunately get issue with browser // cache. // If different applications reuse the same port sometimes user can see previous application. // Make number of port in 'more random' way instead of checking from min to max until find free // port. final int m = min + rnd.nextInt((max - min) + 1); final boolean ev = (m % 2) == 0; int port; if (ev) { port = lookupForward(m, max); if (port < 0) { port = lookupBackward(m, min); } } else { port = lookupBackward(m, min); if (port < 0) { port = lookupForward(m, max); } } return port; }
private int lookupBackward(int max, int min) { for (int port = max; port >= min; port--) { if (checkPort(port)) { return port; } } return -1; }
/** * Get free port from the specified range. Specified range may not be wider than configured range * otherwise IllegalArgumentException is thrown. Configured range may be checked with method * {@link #getRange()}. * * @return free port or {@code -1} if there is no free port * @throws IllegalArgumentException if {@code min > range.first} or if {@code min > range.second} * @see #getRange() * @see #MIN_PORT * @see #MAX_PORT */ public int acquire(int min, int max) { if (min < range.first) { throw new IllegalArgumentException( String.format("Min port value may not be less than %d", range.first)); } if (max > range.second) { throw new IllegalArgumentException( String.format("Max port value may not be greater than %d", range.second)); } return doAcquire(min, max); }