pixel
pixel

Reputation: 26503

Server Sent Events in Spring - why executor service is used there?

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?

Upvotes: 0

Views: 92

Answers (2)

Chasca
Chasca

Reputation: 311

SseEmitter is something you must return straight away in order for your client to know you have started a connection with it and that the server might send some data. The header indicating that from the client side is : Content-Type: text/event-stream (I mean the header the server will send in its 200 OK response).

Thus, programmatically the only way to still be able to use the instance of sseEmitter you have created and returned in your Controller, is to start a new dedicated thread that will push data and eventually stop it at some point. If you don't do that you will never be able to send any data to your client. Because you must answer to your client before sending data in the pipe.

You don't need to use specifically an ExecutorService for that matter, but since it is a good practice for asynchronous tasks I guess that is why the examples talk about it.

Upvotes: 1

itssoumen
itssoumen

Reputation: 142

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.

Upvotes: 1

Related Questions