并发编程-SimpleDateFormat线程不安全及解决办法

一. 为什么SimpleDateFormat不是线程安全的?

Java源码如下:

一. 为什么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 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();
                    }
                }
            });
        }
    }
}

三. 解决方案:

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

转载于:https://my.oschina.net/u/3088173/blog/1503361

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值