Search code examples
javaspringmultithreadingspring-webfluxreactor

Does Spring Webflux invokes single HandlerFunction in a single thread per request?


Considering the snippet below - is it safe to pass simple not thread-safe HashMap to a SomeHandlerFunction that will use it in other autowired beans in SomeHandlerFunction?

@Bean
RouterFunction<ServerResponse> request(SomeHandlerFunction handlerFunction) {
    handlerFunction.setSimpleMapProperties(new HashMap());
    return route(GET("/dummy"), handlerFunction);
}


@Service
class SomeHandlerFunction implements HandlerFunction {
    @Autowired
    List<AnotherBeans> anotherBeans;

    Mono<T> handle(ServerRequest var1) {
        // code...
    }
}

I'm a bit aware about multithreading model in WebFlux, but this case made me confusing.


Solution

  • If that HashMap is mutable, it's not a good idea - not even with Spring MVC. What should you do instead? It really depends on the use case at hand.

    If you're trying to setup a local in-memory cache, you could use a library like Caffeine, or simply a ConcurrentMapCache.

    If you'd like to share configuration keys with that bean, you could wrap that map with Collections.unmodifiableMap or even better, make that a proper immutable POJO.

    If this is meant to carry temporary data that's linked with the request being processed, you should instead use request attributes or Reactor Context for that.