SimpleDateFormat的线程安全问题与解决方案

SimpleDateFormat 是 Java 中一个常用的类,该类用来对日期字符串进行解析和格式化输出,但如果使用不小心会导致非常微妙和难以调试的问题.

因为 DateFormat 和 SimpleDateFormat 类不都是线程安全的,在多线程环境下调用 format() 和 parse() 方法应该使用同步代码来避免问题,
或者使用ThreadLocal, 也是将共享变量变为独享,线程独享肯定能比方法独享在并发环境中能减少不少创建对象的开销。
如果对性能要求比较高的情况下,一般推荐使用这种方法。

 public class DateUtil {

     static final DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

     static ThreadLocal<DateFormat> threadLocal = new ThreadLocal<DateFormat>() {
protected DateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
}
}; private static DateFormat dateFormat() {
// return sdf;
return threadLocal.get();
} public static Date parse(String dateStr) throws ParseException {
return dateFormat().parse(dateStr);
} public static String format(Date date) {
return dateFormat().format(date);
} public static void main(String[] args) {
for (int i = 0; i < 3; i++) {
new Thread() {
public void run() {
while (true) {
try {
Thread.sleep(2000);
} catch (InterruptedException e1) {
e1.printStackTrace();
} try {
System.out.println(this.getName() + ":" + DateUtil.parse("2013-05-24 06:02:20"));
} catch (ParseException e) {
e.printStackTrace();
}
}
}
}.start();
}
}

参考:

http://www.cnblogs.com/zemliu/p/3290585.html

http://www.cnblogs.com/peida/archive/2013/05/31/3070790.html

上一篇:CAShapLayer的使用1


下一篇:跨域、curl、snoopy、file_get_contents()