并发编程-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);     } }

相关文章
相关标签/搜索