5

Spring容器中的Bean是否线程安全?

 3 years ago
source link: https://my.oschina.net/mengwang/blog/5079942
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
Spring容器中的Bean是否线程安全? - 诸葛孔暗的个人空间 - OSCHINA - 中文开源技术交流社区

spring容器中的Bean是否线程安全?

答案是:不安全的 我个人的理解是:

  • 1:在平时的开发中,我们需要定义很多的类型和方法和属性。我们在类中或者其他的类的方法中调用方法的时候,都是用new。创建对象以后就可以调用方法和属性。

  • 2:而springioc容器把这些个bean管理起来,解决了我们的对象创建,管理和依赖的问题。并且是单列的。好处是:可以节约内存空间。坏处也就是:在启动的时候初始化过程会占用一点时间,但是用空间换时间的概念还是值得去牺牲。

  • 3:就是因为springioc创建的bean是单列的(注册列表的方式),这里会引发一个线程安全问题,就是在ioc容器管理的bean中定义成员变量就会引发安全问题。可以使用ThreadLocal解决这个安全问题、

  • 4:对于单例Bean,所有线程都共享一个单例实例Bean,因此是存在资源的竞争(竞争啥:上面有答案了)。

  • 5:比如spring mvc 的 Controller、Service、Dao等,这些Bean大多是无状态的,只关注于方法本身。(关注方法本身?也就是:一个类创建无数个对象调用的方法参数一致其结果都是一致的。)


@Service 
@Slf4j 
public class UserService {
// 这里的User因为userservice是单列的。所以如果多线程执行给name赋值就会覆盖,造成所谓的线程安全问题
private ThreadLocal<User> userInfo=new ThreadLocal<>();
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK