diff --git a/spring-websocket/src/main/java/org/springframework/web/socket/messaging/SubProtocolWebSocketHandler.java b/spring-websocket/src/main/java/org/springframework/web/socket/messaging/SubProtocolWebSocketHandler.java index 99a7378cc48..3bdad972cfc 100644 --- a/spring-websocket/src/main/java/org/springframework/web/socket/messaging/SubProtocolWebSocketHandler.java +++ b/spring-websocket/src/main/java/org/springframework/web/socket/messaging/SubProtocolWebSocketHandler.java @@ -245,6 +245,7 @@ public class SubProtocolWebSocketHandler @Override public final void start() { Assert.isTrue(this.defaultProtocolHandler != null || !this.protocolHandlers.isEmpty(), "No handlers"); + synchronized (this.lifecycleMonitor) { this.clientOutboundChannel.subscribe(this); this.running = true; @@ -256,14 +257,16 @@ public class SubProtocolWebSocketHandler synchronized (this.lifecycleMonitor) { this.running = false; this.clientOutboundChannel.unsubscribe(this); - for (WebSocketSessionHolder holder : this.sessions.values()) { - try { - holder.getSession().close(CloseStatus.GOING_AWAY); - } - catch (Throwable ex) { - if (logger.isWarnEnabled()) { - logger.warn("Failed to close '" + holder.getSession() + "': " + ex); - } + } + + // Proactively notify all active WebSocket sessions + for (WebSocketSessionHolder holder : this.sessions.values()) { + try { + holder.getSession().close(CloseStatus.GOING_AWAY); + } + catch (Throwable ex) { + if (logger.isWarnEnabled()) { + logger.warn("Failed to close '" + holder.getSession() + "': " + ex); } } } @@ -291,6 +294,7 @@ public class SubProtocolWebSocketHandler if (!session.isOpen()) { return; } + this.stats.incrementSessionCount(session); session = decorateSession(session); this.sessions.put(session.getId(), new WebSocketSessionHolder(session));