SpringMVC中,Controller等是否是线程安全的
1、首先,搭建好Spring项目。然后创建对应的Controller、UserService和UserDao类。这里,Controller、UserService和UserDao都定义了自己的变量,分别为a、us和ud。这里,Controller、UserService和UserDao都采用了单例模式。



5、我们对Controller进行ThreadLocal改进(如上图所示),改进后,依然按照先Firefox后Chrome的顺序进行访问:可以看出,a值现在已经是独立的了,Firefox和Chrome各自拥有自己的a值。而没有使用ThreadLocal改造的UserDao和UserService依然存在线程安全问题。

6、ThreadLocal用于改造Session的一个经典例子:private static final ThreadLocal threadSession = new ThreadLocal();public static Session getSession() throws InfrastructureException { Session s = (Session) threadSession.get(); try { if (s == null) { s = getSessionFactory().openSession(); threadSession.set(s); } } catch (HibernateException ex) { throw new InfrastructureException(ex); } return s;}
声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
阅读量:96
阅读量:36
阅读量:67
阅读量:35
阅读量:73