Optimize Jackson resource management in codecs

Prior to this commit, references to `JsonGenerator` and
`ByteArrayBuilder` were not closed/released within codecs calls.
This prevents Jackson from reusing more efficiently shared memory
resources.

This commit properly closes/releases Jackson resources in Spring MVC,
Spring WebFlux and Spring Messaging codecs.
A benchmark on WebFlux codecs (in both single value/streaming mode)
shows significant throughput and allocation improvements for small
payloads.

Closes gh-25910
This commit is contained in:
Brian Clozel
2020-10-20 15:36:23 +02:00
parent db3d537e72
commit 7bee3d1574
5 changed files with 67 additions and 52 deletions

View File

@@ -263,14 +263,15 @@ public class MappingJackson2MessageConverter extends AbstractMessageConverter {
if (byte[].class == getSerializedPayloadClass()) {
ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
JsonEncoding encoding = getJsonEncoding(getMimeType(headers));
JsonGenerator generator = this.objectMapper.getFactory().createGenerator(out, encoding);
if (view != null) {
this.objectMapper.writerWithView(view).writeValue(generator, payload);
try (JsonGenerator generator = this.objectMapper.getFactory().createGenerator(out, encoding)) {
if (view != null) {
this.objectMapper.writerWithView(view).writeValue(generator, payload);
}
else {
this.objectMapper.writeValue(generator, payload);
}
payload = out.toByteArray();
}
else {
this.objectMapper.writeValue(generator, payload);
}
payload = out.toByteArray();
}
else {
// Assuming a text-based target payload