mirror of
https://github.com/spring-projects/spring-boot.git
synced 2026-09-17 20:19:06 +00:00
Update the default implementation of `WritableJson.toByteArray()` to reduce the amount of garbage created from repeated calls. Prior to this commit, each call would create a new `ByteArrayOutputStream` and `OutputStreamWriter` to create the byte array. Writing structured JSON results in many calls to the `toByteArray()` method, which means we repeatedly create and destroy the `ByteArrayOutputStream` and `OutputStreamWriter` objects. Furthermore, both contain buffers that are often expanded and will overlap with each other. The updated implementation uses a custom `Appendable` implementation that uses a single `ByteBuffer` buffer. It also has a `ThreadLocal` cache so that repeated calls from the same thread can reuse the buffer. The cache uses a `SoftReference` to ensure that the JVM can reclaim space if needed (for example, if a large JSON line was written). Closes gh-49428