I wonder why SseEmitter
events are sent inside the executor in most tutorials.
SseEmitter emitter = new SseEmitter();
ExecutorService sseMvcExecutor = Executors.newSingleThreadExecutor();
sseMvcExecutor.execute(() -> { ...
What would happen if they would be run without it?
When you send events inside an executor, the event processing occurs in a separate thread.
Without an Executor, the events are still sent asynchronously because SseEmitter
itself doesn’t block the main thread when you call send()
. But, if your events require processing time or come from an external source (e.g., a message queue or a database fetch), handling everything directly in the main thread will make that thread wait, especially for slow or I/O-bound tasks.
For example -
SseEmitter emitter = new SseEmitter();
try {
emitter.send("Hello, World!");
// Some processing logic --> This will block your main thread !
emitter.send("More data!");
} catch (Exception e) {
emitter.completeWithError(e);
}
return emitter;
using an Executor provides more flexibility and isolation for event generation.