为什么SimpleDateFormat不是线程安全的


Java源码如下:

[java]  view plain  copy
  1. /** 
  2. * Date formats are not synchronized. 
  3. * It is recommended to create separate format instances for each thread. 
  4. * If multiple threads access a format concurrently, it must be synchronized 
  5. * externally. 
  6. */  
  7. public class SimpleDateFormat extends DateFormat {  
  8.       
  9.     public Date parse(String text, ParsePosition pos){  
  10.         calendar.clear(); // Clears all the time fields  
  11.         // other logic ...  
  12.         Date parsedDate = calendar.getTime();  
  13.     }  
  14. }  
  15.   
  16.   
  17. abstract class DateFormat{  
  18.     // other logic ...  
  19.     protected Calendar calendar;  
  20.     public Date parse(String source) throws ParseException{  
  21.         ParsePosition pos = new ParsePosition(0);  
  22.         Date result = parse(source, pos);  
  23.         if (pos.index == 0)  
  24.             throw new ParseException("Unparseable date: \"" + source + "\"" ,  
  25.                 pos.errorIndex);  
  26.         return result;  
  27.     }  
  28. }  
如果我们把SimpleDateFormat定义成static成员变量,那么多个thread之间会共享这个sdf对象, 所以Calendar对象也会共享。

假定线程A和线程B都进入了parse(text, pos) 方法, 线程B执行到calendar.clear()后,线程A执行到calendar.getTime(), 那么就会有问题。


二. 问题重现:

[java]  view plain  copy
  1. public class DateFormatTest {  
  2.     private static SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);  
  3.     private static String date[] = { "01-Jan-1999""01-Jan-2000""01-Jan-2001" };  
  4.   
  5.     public static void main(String[] args) {  
  6.         for (int i = 0; i < date.length; i++) {  
  7.             final int temp = i;  
  8.             new Thread(new Runnable() {  
  9.                 @Override  
  10.                 public void run() {  
  11.                     try {  
  12.                         while (true) {  
  13.                             String str1 = date[temp];  
  14.                             String str2 = sdf.format(sdf.parse(str1));  
  15.                             System.out.println(Thread.currentThread().getName() + ", " + str1 + "," + str2);  
  16.                             if(!str1.equals(str2)){  
  17.                                 throw new RuntimeException(Thread.currentThread().getName()   
  18.                                         + ", Expected " + str1 + " but got " + str2);  
  19.                             }  
  20.                         }  
  21.                     } catch (Exception e) {  
  22.                         throw new RuntimeException("parse failed", e);  
  23.                     }  
  24.                 }  
  25.             }).start();  
  26.         }  
  27.     }  
  28. }  

创建三个进程, 使用静态成员变量SimpleDateFormat的parse和format方法,然后比较经过这两个方法折腾后的值是否相等:

程序如果出现以下错误,说明传入的日期就串掉了,即SimpleDateFormat不是线程安全的:

[plain]  view plain  copy
  1. Exception in thread "Thread-0" java.lang.RuntimeException: parse failed  
  2.     at cn.test.DateFormatTest$1.run(DateFormatTest.java:27)  
  3.     at java.lang.Thread.run(Thread.java:662)  
  4. Caused by: java.lang.RuntimeException: Thread-0, Expected 01-Jan-1999 but got 01-Jan-2000  
  5.     at cn.test.DateFormatTest$1.run(DateFormatTest.java:22)  
  6.     ... 1 more  

三. 解决方案:

1. 解决方案a:

将SimpleDateFormat定义成局部变量:

[java]  view plain  copy
  1. SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);  
  2. String str1 = "01-Jan-2010";  
  3. String str2 = sdf.format(sdf.parse(str1));  
缺点:每调用一次方法就会创建一个SimpleDateFormat对象,方法结束又要作为垃圾回收。


2. 解决方案b:

加一把线程同步锁:synchronized(lock)

[java]  view plain  copy
  1. public class SyncDateFormatTest {  
  2.     private static SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);  
  3.     private static String date[] = { "01-Jan-1999""01-Jan-2000""01-Jan-2001" };  
  4.   
  5.     public static void main(String[] args) {  
  6.         for (int i = 0; i < date.length; i++) {  
  7.             final int temp = i;  
  8.             new Thread(new Runnable() {  
  9.                 @Override  
  10.                 public void run() {  
  11.                     try {  
  12.                         while (true) {  
  13.                             synchronized (sdf) {  
  14.                                 String str1 = date[temp];  
  15.                                 Date date = sdf.parse(str1);  
  16.                                 String str2 = sdf.format(date);  
  17.                                 System.out.println(Thread.currentThread().getName() + ", " + str1 + "," + str2);  
  18.                                 if(!str1.equals(str2)){  
  19.                                     throw new RuntimeException(Thread.currentThread().getName()   
  20.                                             + ", Expected " + str1 + " but got " + str2);  
  21.                                 }  
  22.                             }  
  23.                         }  
  24.                     } catch (Exception e) {  
  25.                         throw new RuntimeException("parse failed", e);  
  26.                     }  
  27.                 }  
  28.             }).start();  
  29.         }  
  30.     }  
  31. }  
缺点:性能较差,每次都要等待锁释放后其他线程才能进入


3. 解决方案c: (推荐)

使用ThreadLocal: 每个线程都将拥有自己的SimpleDateFormat对象副本。

写一个工具类:

[java]  view plain  copy
  1. public class DateUtil {  
  2.     private static ThreadLocal<SimpleDateFormat> local = new ThreadLocal<SimpleDateFormat>();  
  3.   
  4.     public static Date parse(String str) throws Exception {  
  5.         SimpleDateFormat sdf = local.get();  
  6.         if (sdf == null) {  
  7.             sdf = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);  
  8.             local.set(sdf);  
  9.         }  
  10.         return sdf.parse(str);  
  11.     }  
  12.       
  13.     public static String format(Date date) throws Exception {  
  14.         SimpleDateFormat sdf = local.get();  
  15.         if (sdf == null) {  
  16.             sdf = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);  
  17.             local.set(sdf);  
  18.         }  
  19.         return sdf.format(date);  
  20.     }  
  21. }  
测试代码:

[java]  view plain  copy
  1. public class ThreadLocalDateFormatTest {  
  2.     private static String date[] = { "01-Jan-1999""01-Jan-2000""01-Jan-2001" };  
  3.   
  4.     public static void main(String[] args) {  
  5.         for (int i = 0; i < date.length; i++) {  
  6.             final int temp = i;  
  7.             new Thread(new Runnable() {  
  8.                 @Override  
  9.                 public void run() {  
  10.                     try {  
  11.                         while (true) {  
  12.                             String str1 = date[temp];  
  13.                             Date date = DateUtil.parse(str1);  
  14.                             String str2 = DateUtil.format(date);  
  15.                             System.out.println(str1 + "," + str2);  
  16.                             if(!str1.equals(str2)){  
  17.                                 throw new RuntimeException(Thread.currentThread().getName()   
  18.                                         + ", Expected " + str1 + " but got " + str2);  
  19.                             }  
  20.                         }  
  21.                     } catch (Exception e) {  
  22.                         throw new RuntimeException("parse failed", e);  
  23.                     }  
  24.                 }  
  25.             }).start();  
  26.         }  
  27.     }  
  28. }  
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值