Spring Web MVC vs Spring WebFlux. Blocking and Non-blocking
Asked Answered
G

1

8

I'm new at Spring and I'm reading one book "Pro Spring boot 2". It says here that Spring Web MVC has some blocking on each request, and Spring Webflux is a completely non-blocking stack.

  1. Tell me, please, what is meant?
  2. The request that came to Spring MVC activates one thread to execute this request. When and why is it blocked?
  3. And why doesn't Spring WebFlux block thread?
Garratt answered 5/2, 2022 at 10:23 Comment(0)
T
12
  1. Spring Web MVC takes a single thread to handle each request to your API. Spring Webflux does not block a thread to handle each request, because no thread is kept waiting for something to be done (e.g. waiting for an answer from a database).
  2. As written in 1., it can be blocked while waiting for an answer from a database or from another service that is called via HTTP.
  3. Spring Webflux takes advantage of the reactive stack (take a look at https://projectreactor.io/) which is fully non-blocking. This means that no thread is blocked waiting for something to happen. Everything is based on reactive streams publishers (Mono and Flux) making your code reactive to data being available (from a database or from another service called via HTTP as examples).
Thousand answered 5/2, 2022 at 16:48 Comment(4)
Do you want to say, that if one service method sleeps this method for 10 minutes, and 2 users send 2 requests to the server at the same time, then 2 requests will be execute after 2*10=20 minutes?Garratt
That would be true if your service would be handled by a single thread.Cain
And how is it really? It cannot be that one thread processed all requests. Otherwise, Spring MVC would not be so popular and would not be used in production environments. Is there any thread pool? For example, there is 1000 threads in thread pool. If users send 1000 requests , then all threads will be use, and 1001 request will wait until one of the thread get freeGarratt
Yes, there is a thread pool. That is why your application would be able to answer multiple requests even if you use Spring MVC. The issue with Spring MVC is that this thread pool may be more easily exhausted if your application is under heavy load. The reason is that while you do some calls to the database or calls to an external API the thread taking care of the request is blocked waiting for an answer from the database or the external API, meaning it can't handle other requests to your application in the meantime. Using Spring Webflux this does not happen because threads do not block waitingCain

© 2022 - 2024 — McMap. All rights reserved.