Recently I had an issue with embedded-postgres library. I tried to manually pick a free port via
new ServerSocket(0).getLocalPort()
but I was hitting a race condition somewhere (my tests hanged on the second test suite startup).
Then I learned that the library has this capability (of using random port) itself and it didn't have the problem I had. I analyzed the source code and the only difference I found was that they do an additional check:
try (ServerSocket socket = new ServerSocket(0)) {
while(!socket.isBound()) {
Thread.sleep(50);
}
return socket.getLocalPort();
}
So after the port was randomized they wait until it is bound. Code I'm referring to.
I'd like to know why this code is there. My understanding of "binding" was that it's equal to "listening" on a given port, yet here it can't be the case, as this code runs before the server starts. In fact, the server will start (and bind itself) to this exact port. This makes me very confused.