Akhil
Akhil

Reputation: 1254

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.

Upvotes: 5

Views: 424

Answers (4)

Pratik
Pratik

Reputation: 1138

https://gottalovedev.wordpress.com/2014/11/23/bean-scope/

Give this a read. I'm sure it would help.

Upvotes: 1

ecbrodie
ecbrodie

Reputation: 11896

I think this really depends whether you need to store any state in your bean. Usually, I write my singletons so that they contain no state inside of it and are only used to compute business logic. Without state needing to be managed, then it is acceptable to have all threads share that one singleton instance.

Upvotes: 0

Invisible Arrow
Invisible Arrow

Reputation: 4905

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.

Upvotes: 3

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.

Upvotes: 6

Related Questions