Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SpringBoot Single Page Application Concurrency

I have copied a sample Spring Boot SPA. I want to understand, what happens if multiple people use the web page via the URL. Does Java create an instance of the web application per call? Memory resources are not shared, right, i.e. if there is a list object appended to, each user sees their own list?

like image 225
David Jones Avatar asked Sep 01 '26 03:09

David Jones


1 Answers

The default scope for a spring-boot bean is a singleton. Assuming your bean is not managing state you should be fine with the default behavior:

https://docs.spring.io/spring/docs/3.0.0.M3/reference/html/ch04s04.html

4.4.1 The singleton scope

When a bean is a singleton, only one shared instance of the bean will be managed, and all requests for beans with an id or ids matching that bean definition will result in that one specific bean instance being returned by the Spring container.

To put it another way, when you define a bean definition and it is scoped as a singleton, then the Spring IoC container will create exactly one instance of the object defined by that bean definition. This single instance will be stored in a cache of such singleton beans, and all subsequent requests and references for that named bean will result in the cached object being returned.

Now if you are using a bean that's stateful and want a new bean used per request, you can define the scope of that bean to be prototype:

4.4.2 The prototype scope

The non-singleton, prototype scope of bean deployment results in the creation of a new bean instance every time a request for that specific bean is made (that is, it is injected into another bean or it is requested via a programmatic getBean() method call on the container). As a rule of thumb, you should use the prototype scope for all beans that are stateful, while the singleton scope should be used for stateless beans.

like image 82
Always Learning Avatar answered Sep 02 '26 16:09

Always Learning