Search code examples
javaspring-bootjavabeans

Why don't data of different clients mix with singleton beans


I am new to springboot learning, so I have one question. This question might look a bit silly, I am sorry for that before asking a question.

I read that a bean with a singleton scope is created only once in the container. Now my question is that for example if one application has a bean named "Student". Now this application is accessed by 100 different students at the same time. How will this bean keep data of 100 different login students at same time, while it has only one instance? why will it not mix data of all students?


Solution

  • If an object is meant to hold individual data, it cannot be a singleton.

    You are properly asking "How a single instance of a Student class keep data of 100 different students?"

    No, it can't. Singleton beans are meant for objects which should exist only once, such as some kind of application global data, or stateless services, which can exist only once.

    Not everything is a singleton. Spring has also other scopes. And apart from this, many objects' life-cycles are not managed by Spring. The good old constructors are still in use, especially for individual data objects.

    A Spring singleton bean is an object like any other object. The only difference is that its life-cycle is managed by the framework. How you design it and how you handle its fields is completely up to you. The common practice is that it is designed as an immutable object for stateless services or "global constants". However, sometimes you may have a valid reason to make it mutable, but this is not simple and you must be very careful to make it really thread-safe. Don't do it if you don't know to :)

    A good example of a mutable singleton is a application-scope cache, which is often implemented as some kind of a synchronized or concurrent collection.