ThreadLocal示例
本文借花献佛,引用Tim Cull的博文“SimpleDateFormat: Performance Pig”介绍下ThreadLocal的简单使用,同时也对SimpleDateFormat的使用有个深入的了解。
Tim Cull 写道
Just yesterday I came across this problem “in the wild” for the third time in my career so far: an application with performance problems creating tons of java.text.SimpleDateFormat instances. So, I have to get this out there: creating a new instance of SimpleDateFormat is incredibly expensive and should be minimized. In the case that prompted this post, I was using JProfiler to profile this code that parses a CSV file and discovered that 50% of the time it took to suck in the file and make 55,000 objects out of it was spent solely in the constructor of SimpleDateFormat. It created and then threw away a new one every time it had to parse a date. Whew!
“Great,” you think, “I’ll just create one, static instance, slap it in a field in a DateUtils helper class and life will be good.”
Well, more precisely, life will be good about 97% of the time. A few days after you roll that code into production you’ll discover the second cool fact that’s good to know: SimpleDateFormat is not thread safe. Your code will work just fine most of the time and all of your regression tests will probably pass, but once your system gets under a production load you’ll see the occasional exception.
“Fine,” you think, “I’ll just slap a ’synchronized’ around my use of that one, static instance.”
Ok, fine, you could do that and you’d be more or less ok, but the problem is that you’ve now taken a very common operation (date formatting and parsing) and crammed all of your otherwise-lovely, super-parallel application through a single pipe to get it done.
大致意思:Tim Cull碰到一个SimpleDateFormat带来的严重的性能问题,该问题主要有SimpleDateFormat引发,创建一个SimpleDateFormat实例的开销比较昂贵,解析字符串时间时频繁创建生命周期短暂的实例导致性能低下。即使将SimpleDateFormat定义为静态类变量,貌似能解决这个问题,但是SimpleDateFormat是非线程安全的,同样存在问题,如果用‘synchronized’线程同步同样面临问题,同步导致性能下降(线程之间序列化的获取SimpleDateFormat实例)。
Tim Cull使用Threadlocal解决了此问题,对于每个线程SimpleDateFormat不存在影响他们之间协作的状态,为每个线程创建一个SimpleDateFormat变量的拷贝或者叫做副本,代码如下:
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 使用ThreadLocal以空间换时间解决SimpleDateFormat线程安全问题。
* @author
*
*/
public class DateUtil {
private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
@SuppressWarnings("rawtypes")
private static ThreadLocal threadLocal = new ThreadLocal() {
protected synchronized Object initialValue() {
return new SimpleDateFormat(DATE_FORMAT);
}
};
public static DateFormat getDateFormat() {
return (DateFormat) threadLocal.get();
}
public static Date parse(String textDate) throws ParseException {
return getDateFormat().parse(textDate);
}
}
创建一个ThreadLocal类变量,这里创建时用了一个匿名类,覆盖了initialValue方法,主要作用是创建时初始化实例。也可以采用下面方式创建;
//第一次调用get将返回null
private static ThreadLocal threadLocal = new ThreadLocal();
//获取线程的变量副本,如果不覆盖initialValue,第一次get返回null,故需要初始化一个SimpleDateFormat,并set到threadLocal中
public static DateFormat getDateFormat()
{
DateFormat df = (DateFormat) threadLocal.get();
if(df==null){
df = new SimpleDateFormat(DATE_FORMAT)
threadLocal.set(df);
}
return df;
}
我们看下我们覆盖的initialValue方法:
protected T initialValue() {
return null;//直接返回null
}
多个pattern代码如下:
上面这些评论真是搞笑,根本没弄懂瞎评论误导人。 第一:SimpleDateFormat对象压根不能多个线程同时使用,因为它是有状态的,format和parse方法都不能在多线程情况下安全调用。所以一个线程一个SimpleDateFormat是最理想状态 第二:举个实际例子。javaweb开发。一个访问线程进来后,你可能需要在控制层创建一个SimpleDateFormat,然后逻辑层也要用到这个,那么再创建一个,然后持久层也要用到,那么继续创建一个。所以导致了很大的开销。这个时候用ThreadLocal就能解决同一个线程,不同层次之间的数据共享问题。
你的同步只是创建SimpleDateFormat对象的时候同步了,是为了多个线程使用同一个SimpleDateFormat实例。但实际上SimpleDateFormat对象压根不能多个线程同时使用,因为它是有状态的,format和parse方法都不能在多线程情况下安全调用,只是平时一般遇不到问题而已。 你试试开5个下面的线程同时运行。
这里面不是已经加了同步,不过感觉如果加了同步效率不是很理想了
这个代码还是有问题,根本原因在于SimpleDateFormat对象不是线程安全的,所以不能在线程之间共享,除非加上同步机制。正确的思路应该是每个线程下,每个pattern一个SimpleDateFormat对象,这样子就解决问题了。
换到缓存也可以实现。
这个案例解决了一个系统中正真减少创建SimpleDateFormat对象的开销。好思想好思路
是这样的,ThreadLocal相当于保存当前线程的变量,如果一个线程调用format方法N次把DateFormat对象缓存到当前线程里就很有必要了,但是我觉得下面这个方法就没必要用synchronized来同步了: private static ThreadLocal threadLocal = new ThreadLocal() {
protected synchronized Object initialValue() {
return new SimpleDateFormat(DATE_FORMAT);
}
};
用ThreadLocal,n个线程创建n个SimpleDateFormat,不用ThreadLocal。n个线程创建kn个SimpleDateFormat
其实楼主贴出来的使用ThreadLocal的解决方案,依然没有解决SimpleDateFormat创建开销昂贵的问题。
因为ThreadLocal的作用是:使得同一个线程共享一个实例,不同线程使用各自的实例。
对于多线程的情况,依然会创建很多个SimpleDateFormat实例。
既然是2个线程,而ThreadLocal是保证同一线程下获取的对象唯一,2个线程要拿到同一个对象?你看它的普通写法,也没有涉及任何同步,这就和第一个例子矛盾了
比如我现在管理Connection ,2个线程,我同事拿这一个连接,那不死的很惨。
分享下自己的认识,主要在于交流,共同提高;
实在是以空间换了时间,解惑了,谢谢了 我现在积分只有20分,30分才可以投票,要不给你来个精华了
我自己大概想明白了一些,如果在一个线程里面要调
这个方法,调20次的话, 写成SimpleDateFormat s = new SimpleDateFormat(DATE_FORMAT); 这样要创建很多对象,而且这是个工具类,恕我没看清楚 :( 弄成static SimpleDateFormat s = new SimpleDateFormat(DATE_FORMAT); 并发会出问题
这个时候用了ThreadLocal的话,那么只需要在这个线程里实例化一次就ok了,而且多并发也不会出问题。
兄弟 我的意思是这句 private static Map<String, DateFormat> map = new HashMap<String, DateFormat>(); map这个共享对象是非线程安全的 如果你在多线程操作它时会有问题的吧(如set操作)就象你定义一个全局共享的SimpleDateFormat对象一样是非线程安全的啦 private static SimpleDateFormat format= new SimpleDateFormat(“yyyy”);
你改后的代码与我的没什么区别,hashMap虽然是非线性安全的,但是在取instance时,通过synchronized保证只有一个线程进入,并实例化。 附上测试代码:
加这个synchornized 就是由于SimpleDateFormat 是非线程安全 所以要同步 例如 线程a threadlocal.get()方法是这样执行 先获取当前的thread a 然后通过thread a来获取当前线程的 ThreadLocalMap(每个线程都有各自的ThreadLocalMap) 然后以threadlocal为key来get value 由于第一次获取的ThreadLocalMap 是null 此时会调用initialValue方法来new SimpleDateFormat(format) 。注意此时需要同步控制 (因为可能线程b此时也可能做new SimpleDateFormat(format)这个动作 线程a与线程b是同一个同步锁threadlocal ) 注意各个线程用的key都是同一个threadlocal (threadlocal 是static 各个线程是能共享访问的)
其实这样只是保证了在线程a 的整个执行过程中 能获取到同一个SimpleDateFormat对象实例 如果有1000个线程 还是创建了1000个 SimpleDateFormat对象实例
总结使用threadlocal只是为了避免了将这个对象作为参数传递的麻烦
是不是应该这样子呀 import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map;
public class DateUtil {
//private static final String DATE_FORMAT = "yyyy-MM-dd";
private static Map<String, DateFormat> map = new HashMap<String, DateFormat>();
private static String lock = "lock";
public static DateFormat getInstance(String pattern) { DateFormat instance = map.get(pattern); if (instance == null) { synchronized(lock) { // 线程同步,只让一个线程进来实例化 instance = map.get(pattern); // 如果两个线程同时取到的都为null时,其中一个线程实例化后,另一个线程就不需要实例化了 if (instance == null) { instance = new SimpleDateFormat(pattern); //pattern 类似 yyyy-MM-dd 的date format map.put(pattern, instance); } } }
}
public static DateFormat getDateFormat(String pattern) { return getInstance(pattern); }
public static Date parse(String textDate, String pattern) throws ParseException {
}
} 而且 hashmap本身就是非线程安全的 这个在多线程环境下还是有问题吧
貌似有点像单例模式中的懒加载................
单例模式必须同步,因为SimpleDateFormat不是线程安全的,有性能瓶颈
另外,楼主的例子有个问题,就是,SimpleDateFormat的pattern必须是唯一的,实际项目中可能需要各种各样的pattern,怎么处理这个问题?