关于 SimpleDateFormat 的非线程安全问题及其解决方案

1、问题:

先来看一段可能引起错误的代码:

package test.date;
 
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
 
public class ProveNotSafe {
    static SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);
    static String testdata[] = { "01-Jan-1999", "14-Feb-2001", "31-Dec-2007" };
 
    public static void main(String[] args) {
        Runnable r[] = new Runnable[testdata.length];
        for (int i = 0; i < r.length; i++) {
            final int i2 = i;
            r[i] = new Runnable() {
                public void run() {
                    try {
                        for (int j = 0; j < 1000; j++) {
                            String str = testdata[i2];
                            String str2 = null;
                            /* synchronized(df) */{
                                Date d = df.parse(str);
                                str2 = df.format(d);
                                System.out.println("i: " + i2 + "\tj: " + j + "\tThreadID: "
                                        + Thread.currentThread().getId() + "\tThreadName: "
                                        + Thread.currentThread().getName() + "\t" + str + "\t" + str2);
                            }
                            if (!str.equals(str2)) {
                                throw new RuntimeException("date conversion failed after " + j
                                        + " iterations. Expected " + str + " but got " + str2);
                            }
                        }
                    } catch (ParseException e) {
                        throw new RuntimeException("parse failed");
                    }
                }
            };
            new Thread(r[i]).start();
        }
    }
}


结果(随机失败):

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
i: 2    j: 0    ThreadID: 10    ThreadName: Thread- 2    31 -Dec- 2007 31 -Dec- 2007
i: 2    j: 1    ThreadID: 10    ThreadName: Thread- 2    31 -Dec- 2007 31 -Dec- 2007
i: 2    j: 2    ThreadID: 10    ThreadName: Thread- 2    31 -Dec- 2007 31 -Dec- 2007
i: 2    j: 3    ThreadID: 10    ThreadName: Thread- 2    31 -Dec- 2007 31 -Dec- 2007
i: 2    j: 4    ThreadID: 10    ThreadName: Thread- 2    31 -Dec- 2007 31 -Dec- 2007
i: 2    j: 5    ThreadID: 10    ThreadName: Thread- 2    31 -Dec- 2007 31 -Dec- 2007
i: 2    j: 6    ThreadID: 10    ThreadName: Thread- 2    31 -Dec- 2007 31 -Dec- 2007
i: 2    j: 7    ThreadID: 10    ThreadName: Thread- 2    31 -Dec- 2007 31 -Dec- 2007
i: 2    j: 8    ThreadID: 10    ThreadName: Thread- 2    31 -Dec- 2007 31 -Dec- 2007
i: 2    j: 9    ThreadID: 10    ThreadName: Thread- 2    31 -Dec- 2007 31 -Dec- 2007
i: 2    j: 10   ThreadID: 10    ThreadName: Thread- 2    31 -Dec- 2007 31 -Dec- 2007
i: 2    j: 11   ThreadID: 10    ThreadName: Thread- 2    31 -Dec- 2007 31 -Dec- 2007
i: 2    j: 12   ThreadID: 10    ThreadName: Thread- 2    31 -Dec- 2007 31 -Dec- 2007
i: 2    j: 13   ThreadID: 10    ThreadName: Thread- 2    31 -Dec- 2007 31 -Dec- 2007
i: 2    j: 14   ThreadID: 10    ThreadName: Thread- 2    31 -Dec- 2007 31 -Dec- 2007
i: 2    j: 15   ThreadID: 10    ThreadName: Thread- 2    31 -Dec- 2007 31 -Dec- 2007
i: 2    j: 16   ThreadID: 10    ThreadName: Thread- 2    31 -Dec- 2007 31 -Dec- 2007
i: 2    j: 17   ThreadID: 10    ThreadName: Thread- 2    31 -Dec- 2007 11 -Jan- 1999
i: 0    j: 0    ThreadID: 8 ThreadName: Thread- 0    01 -Jan- 1999 11 -Jan- 1999
Exception in thread "Thread-2" i: 1 j: 0    ThreadID: 9 ThreadName: Thread- 1    14 -Feb- 2001 11 -Jan- 2001
Exception in thread "Thread-0" java.lang.RuntimeException: date conversion failed after 0 iterations. Expected 01 -Jan- 1999 but got 11 -Jan- 1999
     at test.date.ProveNotSafe$ 1 .run(ProveNotSafe.java: 30 )
     at java.lang.Thread.run(Thread.java: 619 )
Exception in thread "Thread-1" java.lang.RuntimeException: date conversion failed after 0 iterations. Expected 14 -Feb- 2001 but got 11 -Jan- 2001
     at test.date.ProveNotSafe$ 1 .run(ProveNotSafe.java: 30 )
     at java.lang.Thread.run(Thread.java: 619 )
java.lang.RuntimeException: date conversion failed after 17 iterations. Expected 31 -Dec- 2007 but got 11 -Jan- 1999
     at test.date.ProveNotSafe$ 1 .run(ProveNotSafe.java: 30 )
     at java.lang.Thread.run(Thread.java: 619 )
恩,原因你是知道了,这是由于  SimpleDateFormat 的非线程安全问题引起的,

我们现在简化下问题,错误的代码应该是这样的:

import java.text.SimpleDateFormat;
import java.util.Date;
  
public class DateUtil {
   
 SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
   
 public String formatDate(Date input) {
      return sdf.format(input);
 }
   
}

   

2、解决方

(1)使用局部变量:

import java.text.SimpleDateFormat;
import java.util.Date;
  
public class DateUtil {
   
 private static final String SIMPLE_FORMAT = "dd/MM/yyyy";
   
 public String formatDate(Date input) {
    
  if(input == null){
   return null;
  }
    
  SimpleDateFormat sdf = new SimpleDateFormat(SIMPLE_FORMAT);//local variable
  return sdf.format(input);
 }
}

   


恩,这是线程安全的了,不是吗?

(2)使用 ThreadLocal

这里每个线程将有它自己的 SimpleDateFormat 副本。

<span style="color:#000000;">import java.text.SimpleDateFormat;
import java.util.Date;
  
public class DateUtil {
  
 // anonymous inner class. Each thread will have its own copy of the SimpleDateFormat
 private final static ThreadLocal<simpledateformat> tl = new ThreadLocal<simpledateformat>() {
  protected SimpleDateFormat initialValue() {
   return new SimpleDateFormat("dd/MM/yyyy");
  }
 };<a href="http://my.oschina.net/huangyong/blog/159725" target="_blank" rel="nofollow">http://my.oschina.net/huangyong/blog/159725</a> public String formatDate(Date input) {
  if (input == null) {
   return null;
  }
  
  return tl.get().format(input);
 }
}</span>



PS:顺便聊聊这个 ThreadLocal:

ThreadLocal 按我的理解是一个Map容器,视作其key是当前线程,value就是我们想保证数据安全一致的某对象。从它的功能上来说,应该叫做 ThreadLocalVariable(线程局部变量)更合适些。

具体的含义与作用请参考如下两篇文摘:ThreadLocal 那点事儿

http://blog.csdn.net/zhangming1013/article/details/44018377

http://blog.csdn.net/zhangming1013/article/details/44018395

(3)同步代码块 synchronized(code)

或者使用装饰器设计模式包装下 SimpleDateFormat ,使之变得线程安全。

(4)使用第三方的日期处理函数:

比如 JODA 来避免这些问题你也可以使用 commons-lang 包中的 FastDateFormat 工具类。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值