社区微信群开通啦,扫一扫抢先加入社区官方微信群
社区微信群
首先我们应该知道线程安全问题一般发生在成员变量上,这是为什么啦?
因为成员变量是存放在堆内存中,而堆内存又是线程共享的,这就造成了线程安全问题
因为Spring中的Bean默认是单例的,所以在定义成员变量时也有可能会发生线程安全问题。下面我们就来研究下如何解决Spring中单例Bean的线程安全问题
@RestController
//@Scope("prototype")
public class BeanController {
private int content=0; //基本类型 线程不安全
private String test=null;//引用类型 线程不安全
@RequestMapping("testBean")
public Object getSercurity(){
System.out.println(content);
System.out.println(test);
content=20;
test="单例模式是不安全的";
return test;
}
问题来了,我们该如何测试线程不安全问题啦?我们需要在程序中用debug模式去启动,打断点。不需要执行完程序,然后再次调用该接口。或者多次调用该接口,便会出现以下控制台所示的结果。
解决方式一:
在对应的类名上加上该注解@Scope("prototype"),表示每次调用该接口都会生成一个新的Bean。下图示例
解决方案二 ThreadLocal解决问题
@RestController
//@Scope("prototype")
public class BeanController {
private static ThreadLocal<Integer> content = new ThreadLocal<Integer>() {
@Override
protected Integer initialValue() {
return (int)(Math.random()*10+100);
}
};
private static ThreadLocal<String> test = new ThreadLocal<String>() {
@Override
protected String initialValue() {
return "单例模式是不安全的"+(int)(Math.random()*10+100);
}
};
@RequestMapping("testBean")
public Object getSercurity(){
System.out.println(content.get());
System.out.println(test.get()); System.out.println();
return test.get();
}
}
第三种解决方案:
尽量不要使用成员变量
第四种解决方案:
前提:该程序是web应用,可以使用Spring Bean的作用域中的request,就是说在类前面加上@Scope("request"),表明每次请求都会生成一个新的Bean对象。作用于@Scope("prototype")类似。
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!