SimpleDateFormat是线程不安全的,如果不考虑代价的问题,那么我们完全可在每次需要的时候直接new一个,但是这不是一个很好的解决方式,那么有没有一个相对性能高的办法?
有!一定有,最基本的可以解决问题但是性能上并不一定是最好的,那么我们可以借助ThreadLocal来实现,具体的代码实现如下:
private static ThreadLocal<DateFormat> threadLocal = new ThreadLocal<DateFormat>() {
protected DateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
}
};
在进行get操作的时候直接从threadLocal中获取,代码如下:
public static DateFormat getCommonDateFormat() {
DateFormat sdf = threadLocal.get();
return sdf;
}
跟随源码ThreadLocal的get操作:
public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null)
return (T)e.value;
}
return setInitialValue();
}
我们发现他维护了一个ThreadLocalMap,当此时的thread已经创建过,那么直接返回,没有的话那么执行setInitialValue(),我们看一下setInitialValue我们发现:
private T setInitialValue() {
T value = initialValue();
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
return value;
}
他去初始化一个也就是我们new一个,然后set到相应的map中去。
结论:
1.如果不是重复利用的话其性能未必要,因为每次依然是new,只是说在某线程多次访问此实例的时候性能才会提升。
2.同时我们也发现了一个线程并发的实现方式。