SimpleDateFormat線程不安全及解決辦法

本文轉載至:http://blog.csdn.net/zdp072/article/details/41044059

 

一. 爲什麼SimpleDateFormat不是線程安全的?

Java源碼如下:

/**
* Date formats are not synchronized.
* It is recommended to create separate format instances for each thread.
* If multiple threads access a format concurrently, it must be synchronized
* externally.
*/
public class SimpleDateFormat extends DateFormat {
	
	public Date parse(String text, ParsePosition pos){
		calendar.clear(); // Clears all the time fields
		// other logic ...
		Date parsedDate = calendar.getTime();
	}
}


abstract class DateFormat{
	// other logic ...
	protected Calendar calendar;
	public Date parse(String source) throws ParseException{
        ParsePosition pos = new ParsePosition(0);
        Date result = parse(source, pos);
        if (pos.index == 0)
            throw new ParseException("Unparseable date: \"" + source + "\"" ,
                pos.errorIndex);
        return result;
    }
}

如果我們把SimpleDateFormat定義成static成員變量,那麼多個thread之間會共享這個sdf對象, 所以Calendar對象也會共享。

 

假定線程A和線程B都進入了parse(text, pos) 方法, 線程B執行到calendar.clear()後,線程A執行到calendar.getTime(), 那麼就會有問題。

 

二. 問題重現:

public class DateFormatTest {
	private static SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);
	private static String date[] = { "01-Jan-1999", "01-Jan-2000", "01-Jan-2001" };

	public static void main(String[] args) {
		for (int i = 0; i < date.length; i++) {
			final int temp = i;
			new Thread(new Runnable() {
				@Override
				public void run() {
					try {
						while (true) {
							String str1 = date[temp];
							String str2 = sdf.format(sdf.parse(str1));
							System.out.println(Thread.currentThread().getName() + ", " + str1 + "," + str2);
							if(!str1.equals(str2)){
								throw new RuntimeException(Thread.currentThread().getName() 
										+ ", Expected " + str1 + " but got " + str2);
							}
						}
					} catch (Exception e) {
						throw new RuntimeException("parse failed", e);
					}
				}
			}).start();
		}
	}
}

 

創建三個進程, 使用靜態成員變量SimpleDateFormat的parse和format方法,然後比較經過這兩個方法折騰後的值是否相等:

 

程序如果出現以下錯誤,說明傳入的日期就串掉了,即SimpleDateFormat不是線程安全的:

Exception in thread "Thread-0" java.lang.RuntimeException: parse failed
	at cn.test.DateFormatTest$1.run(DateFormatTest.java:27)
	at java.lang.Thread.run(Thread.java:662)
Caused by: java.lang.RuntimeException: Thread-0, Expected 01-Jan-1999 but got 01-Jan-2000
	at cn.test.DateFormatTest$1.run(DateFormatTest.java:22)
	... 1 more

 

 

三. 解決方案:

 

 

1. 解決方案a:

將SimpleDateFormat定義成局部變量:

SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);
String str1 = "01-Jan-2010";
String str2 = sdf.format(sdf.parse(str1));

缺點:每調用一次方法就會創建一個SimpleDateFormat對象,方法結束又要作爲垃圾回收。

 

 

2. 解決方案b:

加一把線程同步鎖:synchronized(lock)

public class SyncDateFormatTest {
	private static SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);
	private static String date[] = { "01-Jan-1999", "01-Jan-2000", "01-Jan-2001" };

	public static void main(String[] args) {
		for (int i = 0; i < date.length; i++) {
			final int temp = i;
			new Thread(new Runnable() {
				@Override
				public void run() {
					try {
						while (true) {
							synchronized (sdf) {
								String str1 = date[temp];
								Date date = sdf.parse(str1);
								String str2 = sdf.format(date);
								System.out.println(Thread.currentThread().getName() + ", " + str1 + "," + str2);
								if(!str1.equals(str2)){
									throw new RuntimeException(Thread.currentThread().getName() 
											+ ", Expected " + str1 + " but got " + str2);
								}
							}
						}
					} catch (Exception e) {
						throw new RuntimeException("parse failed", e);
					}
				}
			}).start();
		}
	}
}


缺點:性能較差,每次都要等待鎖釋放後其他線程才能進入

 

 

3. 解決方案c: (推薦)

使用ThreadLocal: 每個線程都將擁有自己的SimpleDateFormat對象副本。

寫一個工具類:

public class DateUtil {
	private static ThreadLocal<SimpleDateFormat> local = new ThreadLocal<SimpleDateFormat>();

	public static Date parse(String str) throws Exception {
		SimpleDateFormat sdf = local.get();
		if (sdf == null) {
			sdf = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);
			local.set(sdf);
		}
		return sdf.parse(str);
	}
	
	public static String format(Date date) throws Exception {
		SimpleDateFormat sdf = local.get();
		if (sdf == null) {
			sdf = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);
			local.set(sdf);
		}
		return sdf.format(date);
	}
}

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章