I am using the new HttpClient shipped with JDK 11 to make many requests (to Github's API, but I think that's irrelevant), especially GETs.
For each request, I build and use an HttpClient, like this:
final ExecutorService executor = Executors.newSingleThreadExecutor();
final HttpClient client = client = HttpClient
.newBuilder()
.followRedirects(HttpClient.Redirect.NORMAL)
.connectTimeout(Duration.ofSeconds(10))
.executor(executor)
.build();
try {
//send request and return parsed response;
} finally {
//manually close the specified executor because HttpClient doesn't implement Closeable,
//so I'm not sure when it will release resources.
executor.shutdownNow();
}
This seems to work fine, except every now and then, I get the bellow exception and requests will not work anymore until I restart the app:
Caused by: java.net.ConnectException: Cannot assign requested address
...
Caused by: java.net.BindException: Cannot assign requested address
at java.base/sun.nio.ch.Net.connect0(Native Method) ~[na:na]
at java.base/sun.nio.ch.Net.connect(Net.java:476) ~[na:na]
at java.base/sun.nio.ch.Net.connect(Net.java:468) ~[na:na]
Note that this is NOT the JVM_Bind case.
I am not calling localhost or listening on a localhost port. I am making GET requests to an external API. However, I've also checked the etc/hosts
file and it seems fine, 127.0.0.1
is mapped to localhost
.
Does anyone know why this happens and how could I fix it? Any help would be greatly appreciated.