Picks a port that is not used right at this moment. Warning: Not thread safe. May see "BindException: Address already in use: bind" if using the returned port to create a new server socket when other threads/processes are concurrently creating new sockets without a specific port.
()
| 290 | * creating new sockets without a specific port. |
| 291 | */ |
| 292 | public static int pickUnusedPort() { |
| 293 | try { |
| 294 | ServerSocket serverSocket = new ServerSocket(0); |
| 295 | int port = serverSocket.getLocalPort(); |
| 296 | serverSocket.close(); |
| 297 | return port; |
| 298 | } catch (IOException e) { |
| 299 | throw new RuntimeException(e); |
| 300 | } |
| 301 | } |
| 302 | } |