Does singleton/session scopes of Spring beans require that access to all its fields must be synchronized? Say through "synchronized" keyword or using some classes from package "java.util.concurrent".
As example, is this code not thread safe? (copy/pased from here):
@Component
@SessionScoped
public class ShoppingCart {
private List<Product> items = new ArrayList<Product>();
public List<Product> getAllItems() {
return items;
}
public void addItem(Product item) {
items.add(item);
}
}
When the Spring container creates a bean with the singleton scope, the bean is stored in the heap. This way, all the concurrent threads are able to point to the same bean instance.
Spring singleton beans are NOT thread-safe just because Spring instantiates them.
When beans are application scoped, the same instance of the bean is shared across multiple servlet-based applications running in the same ServletContext, while singleton scoped beans are scoped to a single application context only.
The scope of the Spring singleton is best described as per container and per bean. This means that if you define one bean for a particular class in a single Spring container, then the Spring container will create one and only one instance of the class defined by that bean definition.
When you use singleton
scope from the Spring container, you indicate that all threads that retrieve the bean from the container will use the same instance. So in this case, where the state list of item is shared and modifiable between threads, you would have to synchronize access to the list to protect your application against a ConcurrentModificationException
.
However, the usual practice with Spring is to build your application with stateless objects, which don't have state that will be changing throughout the life of the application.
In the case of session
scope, you might be less likely to see a concurrency problem since the bean will only be accessible by the currently logged in user. However, it's possible (at least on the web) to have multiple requests coming in on the same session, in which case you would need to take the same precautions as if the bean were a singleton.
Again the best way to protect yourself is to try to keep your bean as stateless as possible. If you have a bean that requires state, you should consider using the prototype
scope, which retrieves a new instance of the bean from the container each time.
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