From 4b7cf85d714c514445453845710885c1a8fafffb Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Sun, 2 Nov 2025 20:40:02 +0100 Subject: [PATCH] Retrieve cached response body in a thread-safe manner Closes gh-35745 --- .../BufferingClientHttpResponseWrapper.java | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/spring-web/src/main/java/org/springframework/http/client/BufferingClientHttpResponseWrapper.java b/spring-web/src/main/java/org/springframework/http/client/BufferingClientHttpResponseWrapper.java index a2099e19c78..c3da4d14901 100644 --- a/spring-web/src/main/java/org/springframework/http/client/BufferingClientHttpResponseWrapper.java +++ b/spring-web/src/main/java/org/springframework/http/client/BufferingClientHttpResponseWrapper.java @@ -30,6 +30,7 @@ import org.springframework.util.StreamUtils; * into memory, thus allowing for multiple invocations of {@link #getBody()}. * * @author Arjen Poutsma + * @author Juergen Hoeller * @since 3.1 */ final class BufferingClientHttpResponseWrapper implements ClientHttpResponse { @@ -37,7 +38,7 @@ final class BufferingClientHttpResponseWrapper implements ClientHttpResponse { private final ClientHttpResponse response; @Nullable - private byte[] body; + private volatile byte[] body; BufferingClientHttpResponseWrapper(ClientHttpResponse response) { @@ -62,10 +63,17 @@ final class BufferingClientHttpResponseWrapper implements ClientHttpResponse { @Override public InputStream getBody() throws IOException { - if (this.body == null) { - this.body = StreamUtils.copyToByteArray(this.response.getBody()); + byte[] body = this.body; + if (body == null) { + synchronized (this) { + body = this.body; + if (body == null) { + body = StreamUtils.copyToByteArray(this.response.getBody()); + this.body = body; + } + } } - return new ByteArrayInputStream(this.body); + return new ByteArrayInputStream(body); } @Override