Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring singleton bean

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.

like image 424
Apollo Avatar asked Dec 13 '14 16:12

Apollo


2 Answers

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.

like image 61
chrylis -cautiouslyoptimistic- Avatar answered Sep 19 '22 15:09

chrylis -cautiouslyoptimistic-


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.

like image 21
Invisible Arrow Avatar answered Sep 18 '22 15:09

Invisible Arrow