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

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

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

 1 public class DateUtil {
 2 
 3     static final DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 4 
 5     static ThreadLocal<DateFormat> threadLocal = new ThreadLocal<DateFormat>() {
 6         protected DateFormat initialValue() {
 7             return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 8         }
 9     };
10 
11     private static DateFormat dateFormat() {
12         // return sdf;
13         return threadLocal.get();
14     }
15 
16     public static Date parse(String dateStr) throws ParseException {
17         return dateFormat().parse(dateStr);
18     }
19 
20     public static String format(Date date) {
21         return dateFormat().format(date);
22     }
23 
24     public static void main(String[] args) {
25         for (int i = 0; i < 3; i++) {
26             new Thread() {
27                 public void run() {
28                     while (true) {
29                         try {
30                             Thread.sleep(2000);
31                         } catch (InterruptedException e1) {
32                             e1.printStackTrace();
33                         }
34                         
35                         try {
36                             System.out.println(this.getName() + ":" + DateUtil.parse("2013-05-24 06:02:20"));
37                         } catch (ParseException e) {
38                             e.printStackTrace();
39                         }
40                     }
41                 }
42             }.start();
43         }
44     }

参考:

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

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

原文地址:https://www.cnblogs.com/kofxxf/p/3972727.html