關於 SimpleDateFormat 的非線程安全問題及其解決方案


  一直以來都是直接用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();
        }
    }
}

 

結果(隨機失敗):

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

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");
  }
 };http://my.oschina.net/huangyong/blog/159725 public String formatDate(Date input) {
  if (input == null) {
   return null;
  }
 
  return tl.get().format(input);
 }
}

 

PS:順便聊聊這個 ThreadLocal:

ThreadLocal 按我的理解是一個Map容器,視作其key是當前線程,value就是我們想保證數據安全一致的某對象。從它的功能上來說,應該叫做 ThreadLocalVariable(線程局部變量)更合適些。

具體的含義與作用請參考如下兩篇文摘:ThreadLocal 那點事兒

http://my.oschina.net/huangyong/blog/159489

http://my.oschina.net/huangyong/blog/159725

(3)同步代碼塊 synchronized(code)

或者使用裝飾器設計模式包裝下 SimpleDateFormat ,使之變得線程安全。

(4)使用第三方的日期處理函數:

比如 JODA 來避免這些問題,你也可以使用 commons-lang 包中的 FastDateFormat 工具類。

(5)最后的提問:

上面幾種方案中,有最佳方案嗎?如果不是最佳,各有什么優劣?

PS:

順便吐槽下 java 的日期處理類真TMD是個渣。。。有坑不說,關鍵是難用。。。這點 shell 的 date 命令應該是用戶體驗做的最好的了~ 

REF:

http://java-success.blogspot.com/2012/07/java-coding-question-and-answer-on.html

http://www.codefutures.com/weblog/andygrove/2007/10/simpledateformat-and-thread-safety.html

關於變量的線程安全問題,請參考:

java 線程安全問題之靜態變量、實例變量、局部變量

http://my.oschina.net/leejun2005/blog/130043


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM