首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2EE开发 >

ThreadLocal在J2EE轻量级开发中的使用

2012-12-22 
ThreadLocal在J2EE轻量级开发中的应用ThreadLocal 相当于一个容器,在这个容器中保留了一个个的变量,每一个

ThreadLocal在J2EE轻量级开发中的应用

ThreadLocal 相当于一个容器,在这个容器中保留了一个个的变量,每一个变量是为每一个线程单独存放。

在J2EE轻量级开发中,一般我们分为Action、Service、Model这几层,Action层一般是多态的,所以一般线程安全。而Service和Model是单例的,在这两个层里面一般不会放全局变量,因为这很容易因为多线程造成数据混乱。这时可以用ThreadLocal。

?

public class ShardInfoLocal {//这是一个ThreadLocalprivate static final ThreadLocal<ShardInfo> tl = new ThreadLocal<ShardInfoLocal.ShardInfo>();//设置ThreadLocalpublic static void set(Institutions i){ShardInfo si = new ShardInfo();si.setPrimaryInstitution(i);si.setShards(i.getShardName());tl.set(si);}//移除ThreadLocalpublic static void unset(){tl.remove();}//获取ThreadLocalpublic 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;}}}

热点排行