Skip to content

Commit b5811b8

Browse files
committed
Fix thread-safety issue with shared BinaryMessage in concurrent sessions
- Duplicate ByteBuffer before sending to avoid position conflicts - Ensure thread-safe handling of binary messages across multiple sessions
1 parent 6078946 commit b5811b8

File tree

1 file changed

+11
-1
lines changed

1 file changed

+11
-1
lines changed

spring-websocket/src/main/java/org/springframework/web/socket/handler/ConcurrentWebSocketSessionDecorator.java

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
package org.springframework.web.socket.handler;
1818

1919
import java.io.IOException;
20+
import java.nio.ByteBuffer;
2021
import java.util.Queue;
2122
import java.util.concurrent.LinkedBlockingQueue;
2223
import java.util.concurrent.atomic.AtomicInteger;
@@ -28,6 +29,7 @@
2829
import org.apache.commons.logging.LogFactory;
2930
import org.jspecify.annotations.Nullable;
3031

32+
import org.springframework.web.socket.BinaryMessage;
3133
import org.springframework.web.socket.CloseStatus;
3234
import org.springframework.web.socket.WebSocketMessage;
3335
import org.springframework.web.socket.WebSocketSession;
@@ -194,7 +196,7 @@ private boolean tryFlushMessageBuffer() throws IOException {
194196
}
195197
this.bufferSize.addAndGet(-message.getPayloadLength());
196198
this.sendStartTime = System.currentTimeMillis();
197-
getDelegate().sendMessage(message);
199+
getDelegate().sendMessage(prepareMessage(message));
198200
this.sendStartTime = 0;
199201
}
200202
}
@@ -207,6 +209,14 @@ private boolean tryFlushMessageBuffer() throws IOException {
207209
return false;
208210
}
209211

212+
private WebSocketMessage<?> prepareMessage(WebSocketMessage<?> message) {
213+
if (message instanceof BinaryMessage) {
214+
ByteBuffer payload = ((BinaryMessage) message).getPayload();
215+
return new BinaryMessage(payload.duplicate(), message.isLast());
216+
}
217+
return message;
218+
}
219+
210220
private void checkSessionLimits() {
211221
if (!shouldNotSend() && this.closeLock.tryLock()) {
212222
try {

0 commit comments

Comments
 (0)