I know this question may sound naive, but I have a confusion regarding the scope of bean in web application. I know that for every request a new thread is spawned by the container similarly in case of a spring web application a new thread is spawned for every request, then why it is suggested to define my controller, service as singleton, shouldn't the scope of these beans be prototype, because each request i.e. thread will have their own instance of controller, service to work with.
Please enlighten me.
That would be a huge amount of overhead. There's no reason why each request needs its own service bean if you make your code properly thread-safe, which usually just means not keeping any per-request state on the bean.
Even though a new thread is created (or re-used depending on the configuration), the controller and service instances are re-used. If the controllers and services are designed well, they can be stateless with respect to the request and immutable, which will make them thread-safe. It would also lead to far less object creations when their state is not going to change after their creation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With