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;
}
}
}