SpringMvc的controller是singleton的(非线程安全的)
来源:互联网 发布:全球分红系统源码 编辑:程序博客网 时间:2024/06/05 15:48
和Struts一样,Spring的Controller默认是Singleton的,这意味着每个request过来,系统都会用原有的instance去处理,这样导致了两个结果:一是我们不用每次创建Controller,二是减少了对象创建和垃圾收集的时间;由于只有一个Controller的instance,当多个线程调用它的时候,它里面的instance变量就不是线程安全的了,会发生窜数据的问题。
当然大多数情况下,我们根本不需要考虑线程安全的问题,比如dao,service等,除非在bean中声明了实例变量。因此,我们在使用spring mvc 的contrller时,应避免在controller中定义实例变量。
@RequestMapping("/view")
public class DemoController extends BaseController{
private ThreadLocal<Integer> count = new ThreadLocal<Integer>();
private int k=0;
@RequestMapping(value="sync",method=RequestMethod.GET)
public String indexSync(){
try{
int i = new Random().nextInt(15);
System.out.println(i);
k=i;
count.set(i);
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SS");
System.out.println("-->"+sf.format(new Date())+" Threadname:"+Thread.currentThread().getName());
Thread.sleep(5*1000);
System.out.println("-->1--:"+sf.format(new Date())+" Threadname:"+Thread.currentThread().getName());
synchronized (DemoController.class) {
System.out.println("-->2--:"+sf.format(new Date())+" Threadname:"+Thread.currentThread().getName());
Thread.sleep(10*1000);
}
System.out.println("-->3--:"+sf.format(new Date())+" Threadname:"+Thread.currentThread().getName());
System.out.println("count:"+count.get()+" ,k="+k);
}catch(Exception e){
e.printStackTrace();
}
return "suc";
}
}
结果:
4
-->2016-04-24 00:05:25:957 Threadname:qtp1173631672-26
11
-->2016-04-24 00:05:26:209 Threadname:qtp1173631672-28
-->1--:2016-04-24 00:05:30:958 Threadname:qtp1173631672-26
-->2--:2016-04-24 00:05:30:958 Threadname:qtp1173631672-26
-->1--:2016-04-24 00:05:31:209 Threadname:qtp1173631672-28
-->3--:2016-04-24 00:05:40:959 Threadname:qtp1173631672-26
-->2--:2016-04-24 00:05:40:959 Threadname:qtp1173631672-28
count:4 ,k=11
-->3--:2016-04-24 00:05:50:959 Threadname:qtp1173631672-28
count:11 ,k=11
总结:
1、springmvc的成员是非线程安全的
2、在Controller中使用ThreadLocal变量
3、在spring配置文件Controller中声明 scope="prototype",每次都创建新的controller
所在在使用spring开发web 时要注意,默认Controller、Dao、Service都是单例的。
4、因为springmvc是单例模式,所以影响同时互斥请求
- SpringMvc的controller是singleton的(非线程安全的)
- SpringMvc的controller是singleton的(非线程安全的)
- SpringMvc的controller是singleton的(非线程安全的)
- singleton 线程安全的singleton
- 线程安全的singleton
- 线程安全的singleton
- 线程安全的singleton
- springMVC是线程安全的吗?
- c# SingleTon的线程安全(存档)
- 线程安全的singleton实例
- springMVC的线程安全
- 线程安全的C++的Singleton实现
- 线程安全非线程安全的区别
- SpringMVC和Struts是线程安全的吗?为什么?
- SpringMVC和Struts是线程安全的吗?为什么?
- Spring,SpringMVC,Struts是线程安全的吗
- Reproduced:线程安全的 Singleton - Visual Basic
- 编写线程安全的单件(Singleton)
- 无聊写了个QQ状态查询,但感觉这WSDL不准
- linux下自动检测mongodb 有问题就重启
- 每日170224
- C++ 笔记 关于动态内存分配 (new / delete)
- codeforces 776C Molly's Chemicals(连续子序列和为k的次方的个数)
- SpringMvc的controller是singleton的(非线程安全的)
- Crackme 26
- “此文件来自其他计算机,可能被阻止以帮助保护该计算机” 教你win7解除阻止程序运行怎么操作
- 教你win7解除阻止程序运行怎么操作
- 北京大学校领导接待日完全是“作秀”
- gcc使用---动态库链接静态库
- 比特币 区块链 几种交易标准详解 P2PKH、P2PK、MS、P2SH加密方式
- 【数据结构与算法】B tree 即相关操作 深入解读
- 登入LINUX