Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring: Singleton/session scopes and concurrency

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);
    }
}
like image 469
Alex Siman Avatar asked Nov 17 '09 00:11

Alex Siman


People also ask

How does Spring singleton bean serve concurrent requests?

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.

Are the Spring beans with singleton scope thread-safe?

Spring singleton beans are NOT thread-safe just because Spring instantiates them.

What is the difference between Spring singleton scope and Spring application scope?

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.

What is singleton scope in Spring?

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.


1 Answers

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.

like image 153
Jason Gritman Avatar answered Oct 22 '22 05:10

Jason Gritman