1. 程式人生 > >SimpleDateFormat執行緒不安全及解決辦法

SimpleDateFormat執行緒不安全及解決辦法

一. 為什麼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);
	}
}

測試程式碼:

public class ThreadLocalDateFormatTest {
	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];
							Date date = DateUtil.parse(str1);
							String str2 = DateUtil.format(date);
							System.out.println(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();
		}
	}
}