Video in progress
A Spring `WebSocketHandler` bean is a single instance for all connections. Where do you keep state that belongs to one connection (for example the room the user picked)?
The handler is a singleton, so its fields are shared by every session, and one user's state overwrites another's. I keep state in session attributes, in a ConcurrentHashMap keyed by sessionId, or give each connection its own handler with PerConnectionWebSocketHandler.
📖 Answer
The classic mistake looks like this:
@Component
public class RoomHandler extends TextWebSocketHandler {
private String currentRoom; // WRONG: one field for all connections
@Override
protected void handleTextMessage(WebSocketSession s, TextMessage m) {
currentRoom = parseRoom(m.getPayload());
}
}
Locally, with one tab, everything works. As soon as a second user connects and picks a room, the first user's messages start going to that room too.
There are three correct ways. The simplest, and often enough, is session attributes:
@Override
protected void handleTextMessage(WebSocketSession s, TextMessage m) {
s.getAttributes().put("room", parseRoom(m.getPayload()));
}
A HandshakeInterceptor can pre-populate this map with data from the handshake. When the session closes, the attributes go with it, so no cleanup is needed.
The second is an external map. If other services also need to ask "which room is Ali in?", use a ConcurrentHashMap<String, RoomState> (sessionId → state). Here you must remember to remove entries in afterConnectionClosed, otherwise you have a leak.
The third is PerConnectionWebSocketHandler, which creates a new handler instance for each connection, so fields are safe:
@Bean
PerConnectionWebSocketHandler roomHandler() {
return new PerConnectionWebSocketHandler(RoomHandler.class); // RoomHandler must not be a @Component
}
It creates instances through the BeanFactory, so register it as a @Bean. The cost is one object per connection; keep that in mind at 100,000 connections.
The same rule applies to STOMP: a @Controller is a singleton. Session state lives in SimpMessageHeaderAccessor.getSessionAttributes() or in a bean marked with @Scope(scopeName = "websocket", proxyMode = ScopedProxyMode.TARGET_CLASS); Spring creates a separate one for each WebSocket session.
Sign up to mark studied questions and save your progress.