ThreadLocal 相当于一个容器,在这个容器中保留了一个个的变量,每一个变量是为每一个线程单独存放。
在J2EE轻量级开发中,一般我们分为Action、Service、Model这几层,Action层一般是多态的,所以一般线程安全。而Service和Model是单例的,在这两个层里面一般不会放全局变量,因为这很容易因为多线程造成数据混乱。这时可以用ThreadLocal。
public class ShardInfoLocal {
//这是一个ThreadLocal
private static final ThreadLocal<ShardInfo> tl = new ThreadLocal<ShardInfoLocal.ShardInfo>();
//设置ThreadLocal
public static void set(Institutions i){
ShardInfo si = new ShardInfo();
si.setPrimaryInstitution(i);
si.setShards(i.getShardName());
tl.set(si);
}
//移除ThreadLocal
public static void unset(){
tl.remove();
}
//获取ThreadLocal
public static String firstShard(){
ShardInfo si = tl.get();
if(si != null){
return si.getShards()[0];
}
return null;
}
//ThreadLocal要存放的东西
public static class ShardInfo{
private Institutions primaryInstitution;
private String[] shards;
public Institutions getPrimaryInstitution() {
return primaryInstitution;
}
public void setPrimaryInstitution(Institutions primaryInstitution) {
this.primaryInstitution = primaryInstitution;
}
public String[] getShards() {
return shards;
}
public void setShards(String... shards) {
this.shards = shards;
}
}
}
分享到:
相关推荐
ThreadLocal应用示例及理解,这个写了相关的示例,可以参考一下。
ThreadLocal原理及在多层架构中的应用
ThreadLocal的基本原理,核心机制,源码,ThreadLocal在分布式架构中的应用,ThreadLocal在基础架构,开源中间件,使用非常广泛,建议掌握。
应用ThreadLocal进行多线程处理,经典小例子。可运行。
详解java底层实现原理,ThreadLocal底层实现的数据结构,为什么不会导致内存泄露
ThreadLocal
理解ThreadLocal 理解ThreadLocal 理解ThreadLocal 理解ThreadLocal
ThreadLocal源码以及应用
Java中ThreadLocal的设计与使用.doc
NULL 博文链接:https://bijian1013.iteye.com/blog/2380233
学习ThreadLocal,了解其中的原理,以及学习其中的优点!避免坑点!!
javaee开发常见的模式有MVC模式,在C层中常常会再次分层,如:servlet(web层)、service(业务逻辑层)、dao(数据访问层),其中service和dao最容易混在一起,如转钱交易场景,service层需要执行“事务”操作,会...
ThreadLocal的几种误区ThreadLocal的几种误区ThreadLocal的几种误区
ThreadLocal那点事儿编程开发技术共6页.pdf.zip
正确理解ThreadLocal.pdf
然后基于传统 Servlet 框架搭建一款轻量级 Java Web 框架,一切都是从零开始,逐个实现类加载器、Bean 容器、IoC 框架、MVC 框架,所涉及的代码也是整个框架的核心基础。为了使框架具备 AOP 特性,从代理技术讲到 ...
DbUTils中用ThreadLocal类
ThreadLocal保证一个类的实例变量在各个线程中都有一份单独的拷贝, 从而不会影响其他线程中的实例变量
国内知名的高端IT技术作家,已出版《Spring 2.0宝典》、《基于J2EE的Ajax宝典》、《轻量级J2EE企业应用实战》、《Struts 2权威指南》、《Ruby On Rails敏捷开发最佳实践》等著作。 目录: 第0章 学习Java...