SocketUtils.findAvailableTcpPort() is rather unreliable leading to intermittent test failures because a port is already in use. I'm not sure if this happens because the socket that findAvailableTcpPort opens to get a free port doesn't actually release the port, or if something else just happens to grab the same port. The end result is the same either way.
In the interests of making the build more stable, I'd like to stop using SocketUtils.findAvailableTcpPort() wherever possible. In its place, we should pass in a port of 0 to whatever's going to open a socket, and then use the port that the OS allocates. This will require some changes to some main code, TunnelClient for example, but I think it's worth it to improve the stability of the build.
Comment From: nitinsh99
@wilkinsona we are running into this while using findAvailableTcpPort.. Do you have more insight into why this is unreliable and any code example of providing 0 port? Looking at the SocketUtil implementation, this method tries to open up a server on random port and assumes its available if it doesn't throw IO exception because of conflict; which sounds a pretty good test. So I am curious why it's presenting a flaky behaviour? Also, should this be classified as a bug?
Comment From: wilkinsona
Do you have more insight into why this is unreliable
The opening comment of this issue describes our best guess at why it is unreliable.
Also, should this be classified as a bug?
Not from Spring Boot's perspective asSocketUtils is part of Spring Framework. You may want to open a Spring Framework issue describing the problem that you're seeing.
Comment From: sbrannen
Please note that SocketUtils has been deprecated in Spring Framework 5.3.16:
- https://github.com/spring-projects/spring-framework/issues/28052
Comment From: ahoehma
What can I do if I'm using org.springframework.util.SocketUtils.findAvailableTcpPort()
Comment From: bclozel
@ahoehma this is explained in spring-projects/spring-framework#28052
Comment From: sbrannen
If you have been using SocketUtils solely in testing scenarios, please note that TestSocketUtils will be introduced in Spring Framework 5.3.18. See https://github.com/spring-projects/spring-framework/issues/28210 for details.
Comment From: adrogon
For those arriving here today, this is what you're looking for: https://github.com/spring-projects/spring-framework/pull/29132