Skip to content

Read a declared-length entity into one array in EntityUtils - #1538

Merged
ok2c merged 1 commit into
apache:masterfrom
shinseongsu:entityutils-declared-length
Nov 27, 2026
Merged

ok2c merged 1 commit into
apache:masterfrom
shinseongsu:entityutils-declared-length

Conversation

@shinseongsu

@shinseongsu shinseongsu commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

I was profiling the classic client with async-profiler while comparing it with a few other Java HTTP clients, and EntityUtils.toByteArray stood out on large responses. For a 1 MB body it allocates about 2 MB per call (the ByteArrayBuffer sized to Content-Length, then the toByteArray() copy) and reads the socket in 4 KB chunks, so roughly 256 read() calls per MB. toString adds an 8 KB InputStreamReader buffer, a char[1024] and a CharArrayBuffer on top of that.

With this change, when Content-Length is known and within maxResultLength, the content is read straight into a byte[contentLength] and then read() is called once more to confirm the end of the stream. toString decodes that array with new String(bytes, charset). If the stream turns out to be longer than declared, the bytes already read are handed to the old loop, so the result is the same as before. Unknown length takes the old path unchanged.

Numbers below are the classic client (httpclient5 master) against a Go HTTP/1.1 server on loopback, JDK 21, 60 s per run after a warm-up, two rounds in alternating order. Only the httpcore5 jar differs: 5.5 vs 5.5 with this change (EntityUtils.java in 5.5 is the same as master). Request counts match the server's own counter in every run.

read with body rps alloc / request CPU / request p99
toByteArray 1 MB, 16 in flight 5.2k → 13.1k 1,976 → 983 KB 1,881 → 232 µs 9.6 → 2.5 ms
toByteArray 1 KB, 64 in flight ~145k → ~145k 11.9 → 6.8 KB 30.4 → 29.3 µs 1.39 → 1.36 ms
toString 1 MB, 16 in flight 8.3k → 11.8k 2,941 → 1,921 KB 916 → 311 µs 6.8 → 3.5 ms
toString 1 KB, 64 in flight ~143k → ~143k 19.5 → 8.3 KB 32.5 → 30.8 µs 1.39 → 1.39 ms

At 1 KB the load generator on the same machine is the limit, so the difference there is only allocation. Code that reads getContent() directly isn't affected; this helps EntityUtils and BasicHttpClientResponseHandler users.

round 1

round 2 and CPU flame graphs (1 MB, before / after)

round 2

before

after

Side effects I checked:

  • Old vs new EntityUtils on 300k random inputs (declared length shorter, exact, longer, zero or unknown; different maxResultLength values and charsets; random read sizes; streams that throw at the end). Result, exception and close() are identical except for a stream that is longer than its declared length and also throws at the end, which ContentLengthInputStream can't produce.
  • Failure cases with the classic client and default config, toByteArray and toString: stale pooled connection, connection reset on a reused and on a new connection (GET and POST), body shorter than Content-Length, 503 and 429 with Retry-After, response timeout, connect timeout, connection refused, and 32 requests on the default pool. Same result and the same number of attempts on the server before and after. A truncated body still fails with ConnectionClosedException: Premature end of Content-Length delimited message body.
  • Connection reuse under load: in every run the server saw exactly as many connections as the pool size, before and after, so the body is still fully consumed and the connection goes back to the pool.
  • mvn -pl httpcore5 verify passes (2031 tests), and httpclient5 master passes against the patched core (2892 tests).

Is master enough, or would you like this on 5.4.x too?

When Content-Length is known and within maxResultLength, toByteArray and
toString read the content straight into a byte array of that size instead
of copying it through a 4 KB buffer, a ByteArrayBuffer and a final copy.
Content of unknown length, or longer than declared, takes the old path.
@ok2c

ok2c commented Nov 27, 2026

Copy link
Copy Markdown
Member

@shinseongsu I never cared about EntityUtils and its performance because the entire class should not have existed in the first place. No one in their sane mind should ever buffer InputStream into a byte array and String. One should be consuming data by streaming it from InputStream.

This class exists for some extremely special cases such as content asserts in integration tests.

Master is enough. We are not going to release off 5.4.x anymore unless there is some super severe security issue.

@shinseongsu

Copy link
Copy Markdown
Contributor Author

Thanks for the review and approval! 🙏 Fully agreed on streaming
being the right approach.

For context, I started by trying out the examples on the Getting
Started page, which read the response with EntityUtils.toString().
I then used the same pattern in a side project and noticed it was
slower than expected, which is what led me to look into the
performance and put this PR together. The same pattern also shows
up in the Elasticsearch REST client docs and many tutorials, so I
suspect a lot of users simply follow what the examples show.

Would you be open to a small docs PR that adds a streaming example
(e.g. passing entity.getContent() directly to a JSON parser) and
notes that EntityUtils is meant for small, bounded content only?
Happy to put that together 📝

@ok2c

ok2c commented Nov 27, 2026 •

Copy link
Copy Markdown
Member

Would you be open to a small docs PR that adds a streaming example (e.g. passing entity.getContent() directly to a JSON parser) and notes that EntityUtils is meant for small, bounded content only? Happy to put that together 📝

@shinseongsu I am going to remove old "Quick Start" pages as soon as HttpClient 5.7 has been released. They are just terrible. I do see a few instances of EntityUtilsusage in the new content, though, which is wrong. Basically EntityUtils should never show up anywhere other than test cases. EntityUtils is evil.

Please do feel free to contribute a streaming example. It will be very much appreciated.

@ok2c
ok2c merged commit 4db01fe into apache:master Nov 27, 2026
12 checks passed
@ok2c ok2c added this to the 5.5.1 milestone Nov 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants