Spring:单例/会话范围和并发 [英] Spring: Singleton/session scopes and concurrency

查看:210
本文介绍了Spring:单例/会话范围和并发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Spring bean的singleton /会话范围是否要求对所有字段的访问必须同步?通过synchronized关键字或使用包java.util.concurrent中的一些类来说明。



例如,这个代码不是线程安全的吗? (复制/来自此处):

  @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);
}
}


解决方案

你从Spring容器中使用 singleton scope,你表明从容器中检索bean的所有线程都将使用同一个实例。因此,在这种情况下,项的状态列表在线程之间共享和可修改,您必须同步对列表的访问,以保护您的应用程序免受 ConcurrentModificationException



但是,Spring的通常做法是使用无状态对象构建应用程序,这些对象的状态在应用程序的整个生命周期中都不会改变。 p>

session 作用域的情况下,你可能不太可能看到并发问题,因为bean只能被访问由当前登录的用户。但是,可能(至少在网络上)在同一会话中有多个请求,在这种情况下,您需要采取相同的预防措施,就像bean是单例一样。



同样,保护自己的最好方法是尽可能保持你的bean无状态。如果你有一个需要状态的bean,你应该考虑使用原型作用域,每次从容器中检索一个bean的新实例。


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 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.

这篇关于Spring:单例/会话范围和并发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆