Quick revision
The short answer
Two things are missing. HttpURLConnection's connect and read timeouts default to 0, which means wait forever, so the code must call setConnectTimeout and setReadTimeout. And a connection is only returned to the keep-alive cache for reuse when the response body is read completely and the stream closed, including the error stream for 4xx and 5xx responses, where getInputStream() throws, so we check getResponseCode() first. HttpURLConnection is not deprecated, but it is an old, blocking API without HTTP/2; new code should use java.net.http.HttpClient or Spring's RestClient.
What to remember
In this answer, we fixed legacy HttpURLConnection code. Its connect and read timeouts default to 0, which is infinite, so we set both before connecting. Connections are reused only when the body, or the error stream for 4xx and 5xx responses, is read fully and closed, and getInputStream() throws for error statuses, so we check getResponseCode() first and avoid disconnect(). We checked the global sun.net and http system properties that shape the old stack, and replaced it with java.net.http.HttpClient or Spring's RestClient.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
Two things are missing. HttpURLConnection's connect and read timeouts default to 0, which means wait forever, so the code must call setConnectTimeout and setReadTimeout. And a connection is only returned to the keep-alive cache for reuse when the response body is read completely and the stream closed, including the error stream for 4xx and 5xx responses, where getInputStream() throws, so we check getResponseCode() first. HttpURLConnection is not deprecated, but it is an old, blocking API without HTTP/2; new code should use java.net.http.HttpClient or Spring's RestClient.
Why this question is asked
HttpURLConnection has been in Java since version 1.1, and a lot of code that is still running today was written with it. It works, but it has defaults that were reasonable in the nineties and are dangerous now, and its connection reuse depends on details most callers never knew about. Interviewers ask this to see whether we can read legacy code, spot exactly what is wrong, and know the modern replacement. In this answer, we will look at the typical legacy code, fix the timeouts, fix connection reuse and error handling, check the system properties that affect the old stack, and then rewrite it with the modern clients.
1The Legacy Code and What It Gets Wrong
Here is the kind of code the question describes, the way it appears in many old services.
Notice four problems. There are no timeouts, so a slow service blocks the thread forever. Only one line is read and the stream is never closed, so the connection cannot be reused. If the service answers 404 or 500, getInputStream() throws, and the error response is never read either. And the reader uses the platform default charset instead of the response's charset, which in practice should be UTF-8 for JSON. The first two explain the symptoms in the question exactly.
2Why Threads Hang: Timeouts Default to Infinite
HttpURLConnection has two timeouts, and both default to 0, which the documentation defines as an infinite timeout. The connect timeout limits establishing the connection; the read timeout limits how long each read waits for data, and it also covers the TLS handshake and waiting for the response headers. With neither set, a server that accepts the connection and then stalls holds our thread indefinitely, and enough of those exhaust the service's thread pool.
Both must be set before connecting, that is, before the first call to getResponseCode(), getInputStream() or getOutputStream(). The read timeout is per read, not for the whole response, so it does not protect against a server that trickles bytes slowly; the old API has no overall request timeout, which is one of the reasons to move to the modern client.
3Why Connections Are Not Reused: Keep-Alive Rules
HttpURLConnection does reuse connections, through an internal keep-alive cache, but only under strict conditions. A connection goes back to the cache only when the response body has been read to the end and the stream has been closed. If we read part of the body and abandon it, the connection still has unread bytes, so it cannot carry another request and is eventually closed. Our legacy code reads one line and never closes the stream, so every request opens a new TCP connection and, for HTTPS, a new TLS handshake, which is slow and can exhaust ports under load.
Error responses follow the same rule. For a status of 400 or above, getInputStream() throws an IOException, a FileNotFoundException for 404, and the error body is available from getErrorStream() instead. If we never read and close the error stream, that connection is lost too. Finally, calling disconnect() tells the class we do not plan more requests to that server and may close the underlying socket, so code that calls it after every request also defeats reuse.
- Call getResponseCode() firstno exception for 4xx/5xx
- Status below 400?YesRead getInputStream()NoRead getErrorStream()
- Body read to the end and stream closed?YesNext checkNoSocket discarded: new connection next time
- disconnect() called?YesSocket may be closedNoReturned to keep-alive cache
4 steps in order. Play them, or step through them one at a time.
Reuse needs a fully read, closed body on both the success and the error path.
4The Fixed Version
Putting it together, we set timeouts, check the status first, read the right stream fully with try-with-resources, and do not call disconnect().
Notice that getErrorStream() can return null when the server sent no body, so we handle that case. readAllBytes(), available since Java 9, guarantees the stream is drained. With this version, a second call to the same host reuses the cached connection instead of opening a new one.
5System Properties That Shape the Old Stack
The old stack is also configured globally through system properties, which is worth checking because a forgotten -D flag can change behaviour for every HttpURLConnection in the JVM. http.keepAlive turns keep-alive on or off (default true), and http.maxConnections sets how many idle connections are cached per destination (default 5). sun.net.client.defaultConnectTimeout and sun.net.client.defaultReadTimeout set JVM-wide default timeouts in milliseconds, which is a useful safety net for legacy code we cannot change immediately. http.proxyHost, http.proxyPort, https.proxyHost and http.nonProxyHosts control proxies. And sun.net.http.retryPost, true by default, makes the old stack silently resend a POST once in some failure cases, which can duplicate a non-idempotent request; setting it to false is often wise. These sun.net names are implementation properties, so check your JDK's networking properties documentation.
6What Replaces HttpURLConnection
HttpURLConnection is not deprecated, but it is legacy: blocking, HTTP/1.1 only, with mutable state and awkward error handling. Java 11 added java.net.http.HttpClient, which supports HTTP/2, asynchronous calls, a request timeout and a proper connection pool. In Spring applications, RestClient, added in Spring Framework 6.1, is the modern synchronous client, with a fluent API on top of a pluggable HTTP library.
Both clients manage connection reuse for us, and both should be created once and shared, because creating a client per request throws its connection pool away each time.
7Follow-up questions
Which Spring classes still use HttpURLConnection by default?
SimpleClientHttpRequestFactory is built on HttpURLConnection, and a RestTemplate created with new RestTemplate() uses it. Spring Boot's RestTemplateBuilder and RestClient builder detect HTTP libraries on the class path, such as Apache HttpClient 5, Jetty or Reactor Netty, and in recent versions the JDK HttpClient, and fall back to SimpleClientHttpRequestFactory only when nothing better is found; the detection order has changed between versions, so check yours. Resource loading through UrlResource also opens URL connections.
Is setting sun.net.client.defaultReadTimeout enough as a fix?
It is a good emergency safety net, because it gives every HttpURLConnection in the JVM a default without code changes. But it is still a per-read timeout, it applies to code that needs longer limits too, and it does nothing for connection reuse, so the code still needs fixing.
Why does readLine() break reuse when the body is a single line?
Because the stream was not read to its end and not closed. Even if the line was the whole body, the connection only learns the body is finished when it reaches the end of the stream and the stream is closed.
8Conclusion
In this answer, we fixed legacy HttpURLConnection code. Its connect and read timeouts default to 0, which is infinite, so we set both before connecting. Connections are reused only when the body, or the error stream for 4xx and 5xx responses, is read fully and closed, and getInputStream() throws for error statuses, so we check getResponseCode() first and avoid disconnect(). We checked the global sun.net and http system properties that shape the old stack, and replaced it with java.net.http.HttpClient or Spring's RestClient.
Open with
The code has two problems that match the symptoms. First, HttpURLConnection's connect timeout and read timeout both default to zero, which means infinite, so a slow or stalled service blocks the thread forever.
Then, if they want more
I would call setConnectTimeout, say 2000 milliseconds, and setReadTimeout, say 5000, before connecting. The read timeout is per read, so it does not limit the whole response. Second, connection reuse. The old stack only puts a connection back into its keep-alive cache when the body has been read to the end and the stream closed.
This code reads one line and never closes anything, so every request opens a new connection and TLS handshake. For error statuses, getInputStream throws, so I would call getResponseCode first, read getErrorStream for 400 and above, drain it fully with try-with-resources, and not call disconnect, which can close the socket.
I would also check the global system properties the old stack uses, like http.keepAlive, http.maxConnections, the sun.net default timeouts, the proxy properties, and sun.net.http.retryPost, which can silently resend a POST. HttpURLConnection is not deprecated, but it is legacy, blocking and HTTP/1.1 only. For new code I would use java.net.http.HttpClient, or in Spring, RestClient, created once and shared, with explicit timeouts.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 11, Java 20, Java 9, Spring Framework 6
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- The Java Language Specification, Java SE 21, Java SE 21 API documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Legacy code calls a REST service with HttpURLConnection. Threads hang forever when the...": https://scrivio-interview-library.netlify.app/java/networking/dee6bed3d7/