A Spring WebSocket STOMP client sends a long
to Spring WebSocket STOMP server that immediately returns the same value. When the client completes sending, it exits its main thread and the client terminates as expected.
If I enable STOMP heartbeats:
webSocketStompClient.setTaskScheduler( new DefaultManagedTaskScheduler() ); webSocketStompClient.setDefaultHeartbeat( new long[] {10_000, 10_000} );
the client no longer exits the JVM when the client’s main thread finishes because the DefaultManagedTaskScheduler
task-scheduler started a non-daemon thread (“pool-2-thread-1”).
I don’t want to exit via System.exit
, so how can the keep-alive task-scheduler be shutdown so the client terminates when the main thread finishes?
Advertisement
Answer
TL;DR
Build and keep the JDKs executor and shut down the executor when finished.
Details:
public class MyTaskScheduler { private final ScheduledExecutorService executor; private final ConcurrentTaskScheduler scheduler; public MyTaskScheduler() { executor = Executors.newScheduledThreadPool(1); scheduler = new ConcurrentTaskScheduler(executor); } public TaskScheduler taskScheduler() { return scheduler; } public void shutdown() { executor.shutdown(); } }
In the appropriate context, construct and keep the new task-scheduler:
MyTaskScheduler myTaskScheduler = new MyTaskScheduler();
And use the new task-scheduler instance for heartbeats:
webSocketStompClient.setTaskScheduler( myTaskScheduler ); webSocketStompClient.setDefaultHeartbeat( new long[] {10_000, 10_000} );
When application is finished shut down the executor:
myTaskScheduler.shutdown();