SimpleDateFormat 是非線程安全的
我們經常使用一些單例處理的實例作爲工具類基礎,然而SimpleDateFormat的單例實例在在併發情況下回出現各種靈異錯誤。
原因是因爲SimpleDateFormat不是線程安全的。我們之所以忽視線程安全的問題,是因爲從SimpleDateFormat提供的接口看不出來它是非線程安全的
只是在JDK文檔的類註釋有如下說明: Date formats are not synchronized.
推薦(建議)爲每個線程創建獨立的格式實例。如果多個線程同時訪問一個格式,則它必須保持外部同步
* </table>
* </blockquote>
*
* <h4><a name="synchronization">Synchronization</a></h4>
*
* <p>
* 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.
*
* @see <a href="https://docs.oracle.com/javase/tutorial/i18n/format/simpleDateFormat.html">Java Tutorial</a>
* @see java.util.Calendar
* @see java.util.TimeZone
* @see DateFormat
* @see DateFormatSymbols
* @author Mark Davis, Chen-Lieh Huang, Alan Liu
*/
public class SimpleDateFormat extends DateFormat {
SimpleDateFormat繼承了DateFormat,在DateFormat中定義了一個protected屬性的 Calendar類的對象:calendar
Calendar類的的功能牽扯到時區與本地化等等,Jdk的實現中使用了成員變量來傳遞參數,這就造成在多線程的時候會出現錯誤。
// Called from Format after creating a FieldDelegate
private StringBuffer format(Date date, StringBuffer toAppendTo,
FieldDelegate delegate) {
// Convert input date to time field list
calendar.setTime(date);
boolean useDateFormatSymbols = useDateFormatSymbols();
for (int i = 0; i < compiledPattern.length; ) {
int tag = compiledPattern[i] >>> 8;
int count = compiledPattern[i++] & 0xff;
if (count == 255) {
count = compiledPattern[i++] << 16;
count |= compiledPattern[i++];
}
switch (tag) {
case TAG_QUOTE_ASCII_CHAR:
toAppendTo.append((char)count);
break;
case TAG_QUOTE_CHARS:
toAppendTo.append(compiledPattern, i, count);
i += count;
break;
default:
subFormat(tag, count, delegate, toAppendTo, useDateFormatSymbols);
break;
}
}
return toAppendTo;
}
線程不安全原因分析:
calendar.setTime(date)這條語句改變了calendar,稍後,calendar還會用到(在subFormat方法裏),而這就是引發問題的根源。想象一下,在一個多線程環境下,有兩個線程持有了同一個SimpleDateFormat的實例,分別調用format方法:
1. 線程1進來,調用format方法,改變了calendar
2. 中斷
3. 線程2進來,開始執行,改變了calendar
4. 中斷
5. 回到線程1,此時,calendar已然不是它所設的值,而是走上了線程2設計的道路。
- 結論:如果多個線程同時爭搶calendar對象,則會出現各種問題,時間不對,線程掛死等等。而SimpleDateFormat的實現用到成員變量calendar,唯一的好處,就是在調用subFormat時,少了一個參數,卻帶來了這許多的問題。
這裏要提到的就是如何判斷線程安全的方法標準了:那便是無狀態,如果方法裏面存在狀態,並且可以被改變的情況的話,開發者就必須要考慮併發情況下的線程安全問題了
無狀態方法的好處之一,就是它在各種環境下,都可以安全的調用。衡量一個方法是否是有狀態的,就看它是否改動了其它的東西,比如全局變量,比如實例的字段。format方法在運行過程中改動了SimpleDateFormat的calendar字段,所以,它是有狀態的。
開發過程中使用SimpleDateFormat的線程安全的使用方案
- 需要的時候創建新實例,對實例內存什麼的不存在太多要求的小應用推薦使用
- 使用synchronized:同步SimpleDateFormat對象,缺點,高併發併發下存在性能問題
- 使用ThreadLocal將共享變量變爲線程獨享
- 拋棄JDK,使用其他類庫中的時間格式化類:推薦Apache commons 裏的FastDateForma 以及 Joda-Time類庫
以下是測試代碼:
package cn.coremail;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @author linbingcheng
* @version V1.0
* @Title: UnsafeDateUtils
* @Description: TODO
* @email [email protected]
* @date 2018/6/26
*/
public class UnsafeDateUtils {
// public static String formatDate(Date date)throws ParseException {
// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// return sdf.format(date);
// }
//
// public static Date parse(String strDate) throws ParseException{
// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// return sdf.parse(strDate);
// }
private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static String formatDate(Date date)throws ParseException{
return sdf.format(date);
}
public static Date parse(String strDate) throws ParseException{
return sdf.parse(strDate);
}
}
package cn.coremail;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* @author linbingcheng
* @version V1.0
* @Title: SafeDateUtils
* @Description: TODO
* @email [email protected]
* @date 2018/7/3
*/
public class SafeDateUtils {
/** 鎖對象 */
private static final Object lockObj = new Object();
private static Map<String, ThreadLocal<SimpleDateFormat>> sdfMap = new HashMap<String, ThreadLocal<SimpleDateFormat>>();
private static final String YYYYMMDDHHMMSS = "yyyy-MM-dd HH:mm:ss";
private static SimpleDateFormat getSdf(final String pattern) {
ThreadLocal<SimpleDateFormat> tl = sdfMap.get(pattern);
// 此處的雙重判斷和同步是爲了防止sdfMap這個單例被多次put重複的sdf
if (tl == null) {
synchronized (lockObj) {
tl = sdfMap.get(pattern);
if (tl == null) {
// 這裏是關鍵,使用ThreadLocal<SimpleDateFormat>替代原來直接new SimpleDateFormat
tl = new ThreadLocal<SimpleDateFormat>() {
@Override
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat(pattern);
}
};
sdfMap.put(pattern, tl);
}
}
}
return tl.get();
}
public static String formatDate(Date date, String pattern) throws ParseException {
return getSdf(pattern).format(date);
}
public static Date parse(String strDate, String pattern) throws ParseException {
return getSdf(pattern).parse(strDate);
}
}
package cn.coremail;
import java.text.ParseException;
import java.util.Date;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
/**
* @author linbingcheng
* @version V1.0
* @Title: DateUtilTest
* @Description: TODO
* @email [email protected]
* @date 2018/6/26
*/
public class DateUtilTest {
static CyclicBarrier cyclicBarrier = new CyclicBarrier(5);
public static class TestSimpleDateFormatThreadSafe extends Thread {
@Override
public void run() {
System.out.println(this.getName() + ": is running");
try {
cyclicBarrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
while(true) {
try {
// System.out.println(this.getName() + ":" + UnsafeDateUtils.parse("2018-06-24 06:02:20 "));
System.out.println(this.getName() + ":" + SafeDateUtils.parse("2018-06-24 06:02:20 ","yyyy-MM-dd HH:mm:ss"));
} catch (ParseException e) {
e.printStackTrace();
}
try {
this.join(1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
yield();
}
}
}
public static void main(String[] args) {
for(int i = 0; i < 5; i++){
new TestSimpleDateFormatThreadSafe().start();
}
}
}