Search code examples
javaspringconcurrencyproject-reactorreactive-streams

Is it safe to use the same FluxSink from multiple threads concurrently


I know a Publisher must not publish concurrently, but if I use Flux#create(FluxSink), can I safely call FluxSink#next concurrently?

In other words, does Spring have internal magic that ensures proper serial publishing of events even if FluxSink#next is called concurrently?

public class FluxTest {

    private final Map<String, FluxSink<Item>> sinks = new ConcurrentHashMap<>();

    // Store a new sink for the given ID
    public void start(String id) {
        Flux.create(sink -> sinks.put(id, sink));
    }

    // Called from different threads
    public void publish(String id, Item item) {
        sinks.get(id).next(item); //<----------- Is this safe??
    }
}

It sounds to me like this paragraph in the official guide indicates that the above is indeed safe, but I'm not very confident in my understanding.

create is a more advanced form of programmatic creation of a Flux which is suitable for multiple emissions per round, even from multiple threads.


Solution

  • Yes, Flux.create produces a SerializedSink that is safe to use from multiple threads for next calls