併發編程-SimpleDateFormat線程不安全及解決辦法

一. 爲何SimpleDateFormat不是線程安全的?java

Java源碼以下:安全

一. 爲何SimpleDateFormat不是線程安全的?ide

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對象也會共享。.net

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

二. 問題重現:orm

public class SdfThreadTest2{
    public static void main(String[] args) throws InterruptedException {
        final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        final String[] date = new String[]{"2017-01-01","2017-02-02","2017-03-03","2017-04-04","2017-05-05",
                "2017-06-06","2017-07-07","2017-08-08","2017-09-09","2017-10-10","2017-11-11","2017-12-12"};
        final ExecutorService es2 = Executors.newFixedThreadPool(12);
        for(int i=0;i<12;i++){
            final int j = i;
            es2.execute(new Runnable(){對象

                @Override
                public void run() {
                    try {
                        System.out.println(j+ "->" + sdf.parse((date[j])));
                    } catch (ParseException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            });
        }
    }
}ip

三. 解決方案:

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 SdfThreadTest2{
    public static void main(String[] args) throws InterruptedException {
        final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        final String[] date = new String[]{"2017-01-01","2017-02-02","2017-03-03","2017-04-04","2017-05-05",
                "2017-06-06","2017-07-07","2017-08-08","2017-09-09","2017-10-10","2017-11-11","2017-12-12"};
        final ExecutorService es2 = Executors.newFixedThreadPool(12);
        for(int i=0;i<12;i++){
            final int j = i;
            es2.execute(new Runnable(){

                @Override
                public void run() {
                    try {
                        synchronized(sdf){
                            System.out.println(j+ "->" + sdf.parse((date[j])));
                        }
                    } catch (ParseException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            });
        }
    }
}

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

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);     } }

相關文章
相關標籤/搜索