SimpleDateFormat线程不安全及解决办法

9 篇文章 0 订阅
昨天知道了findbugs这个工具 而且用这个工具找到了潜在几个问题,有一个是便利map用的keyset  findbugs建议改成entrtyset,还有一个就是 SimpleDateFormat不是线程安全的:

As the JavaDoc states, DateFormats are inherently unsafe for multithreaded use. The detector has found a call to an instance of DateFormat that has been obtained via a static field. This looks suspicous.

其实,出现这种问题的代码一般都长得差不多,典型的代码示例如下:

public class Test{
     private SimpleDateFormat dateFormat  = new SimpleDateFormat("yyyy-MM-dd");
     public void method1(){
         dateFormat.format(new Date());
     }
     public void method2(){
         dateFormat.format(new Date());
     }
 )

再给个详细例子说明问题,看下面代码:

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class SimpleDateFormatTest {
    public static void main(String[] args) {
        SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
        Date today=new  Date();
        Date tomorrow=new Date(today.getTime()+1000*60*60*24);
          System.out.println(today); // 今天是2010-01-11
          System.out.println(tomorrow); // 明天是2010-01-11
          Thread thread1=new Thread(new Thread1(dateFormat,today));
          thread1.start();
          Thread thread2 = new Thread(new Thread2(dateFormat,tomorrow));
          thread2.start();
}

}
class Thread1 implements Runnable{

     private SimpleDateFormat dateFormat;
     private Date date;
    
    
     public Thread1(SimpleDateFormat dateFormat,Date date) {
         this.dateFormat = dateFormat;
         this.date = date;
    }
     
    @Override
    public void run() {
        // TODO Auto-generated method stub
        for(;;){
            String strDate=dateFormat.format(date);
            if(!"2016-09-30".equals(strDate)){
                System.err.println("today="+strDate);
                System.exit(0);
            }
        }
    }
    
}

class Thread2 implements Runnable{
    private SimpleDateFormat dateFormat;
    private Date date;
    public Thread2(SimpleDateFormat dateFormat,Date date){
        this.dateFormat = dateFormat;
        this.date = date;
    }
    public void run() {
        for(;;){
            String strDate = dateFormat.format(date);
            if(!"2016-10-01".equals(strDate)){
                System.err.println("tomorrow="+strDate);
                System.exit(0);
            }
        }
    }
}

运行的结果如下:

Fri Sep 30 11:06:49 CST 2016
Sat Oct 01 11:06:49 CST 2016
today=2016-10-01

错得很明显了

解决方案:

1. 解决方案a:

将SimpleDateFormat定义成局部变量:

  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)

  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对象副本。

写一个工具类:

  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. }  
测试代码:

  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.     }  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值