SimpleDateFormat线程安全问题

一、背景

项目上线前QA进行压测,出现SimpleDateFormat线程安全问题,异常如下

Exception in thread "Thread-1" java.lang.NumberFormatException: multiple points
    at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1082)
    at java.lang.Double.parseDouble(Double.java:510)
    at java.text.DigitList.getDouble(DigitList.java:151)
    at java.text.DecimalFormat.parse(DecimalFormat.java:1302)
    at java.text.SimpleDateFormat.subParse(SimpleDateFormat.java:1589)
    at java.text.SimpleDateFormat.parse(SimpleDateFormat.java:1311)
    at java.text.DateFormat.parse(DateFormat.java:335)
    at com.peidasoft.orm.dateformat.DateNoStaticUtil.parse(DateNoStaticUtil.java:17)
    at com.peidasoft.orm.dateformat.DateUtilTest$TestSimpleDateFormatThreadSafe.run(DateUtilTest.java:20)
Exception in thread "Thread-0" java.lang.NumberFormatException: multiple points
    at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1082)
    at java.lang.Double.parseDouble(Double.java:510)
    at java.text.DigitList.getDouble(DigitList.java:151)
    at java.text.DecimalFormat.parse(DecimalFormat.java:1302)
    at java.text.SimpleDateFormat.subParse(SimpleDateFormat.java:1589)
    at java.text.SimpleDateFormat.parse(SimpleDateFormat.java:1311)
    at java.text.DateFormat.parse(DateFormat.java:335)
    at com.peidasoft.orm.dateformat.DateNoStaticUtil.parse(DateNoStaticUtil.java:17)
    at com.peidasoft.orm.dateformat.DateUtilTest$TestSimpleDateFormatThreadSafe.run(DateUtilTest.java:20)

二、问题分析

SimpleDateFormat继承自DateFormat,而在最常用的parse()和format()方法的内部,会调用父类DateFormat内部的calendar,
如parse()方法内部有一段这样的代码
	start = subParse(text, start, tag, count, obeyCount,
                 ambiguousYear, pos,
                 useFollowingMinusSignAsDelimiter, calb);
其内部实现比较复杂,但很明显它调用了父类DateFormat内部的calendar对象,那就大概理解到问题了,当我们的SimpleDateFormat对象声明为static的时候,在多线程并发的时候就会共享这个format对象,也就共用了calendar这个对象。
	public static final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
再继续下面代码中调用了CalendarBuilder类的establish的方法
	parsedDate = calb.establish(calendar).getTime();
            // If the year value is ambiguous,
            // then the two-digit year == the default start year
            if (ambiguousYear[0]) {
                if (parsedDate.before(defaultCenturyStart)) {
                    parsedDate = calb.addYear(100).establish(calendar).getTime();
                }
            }
可以看到其内部调用了坑爹的clear()重置了一下
	Calendar establish(Calendar cal) {
        boolean weekDate = isSet(WEEK_YEAR)
                            && field[WEEK_YEAR] > field[YEAR];
        if (weekDate && !cal.isWeekDateSupported()) {
            // Use YEAR instead
            if (!isSet(YEAR)) {
                set(YEAR, field[MAX_FIELD + WEEK_YEAR]);
            }
            weekDate = false;
        }

        cal.clear();
        // Set the fields from the min stamp to the max stamp so that
        // the field resolution works in the Calendar.
        for (int stamp = MINIMUM_USER_STAMP; stamp < nextStamp; stamp++) {
            for (int index = 0; index <= maxFieldIndex; index++) {
                if (field[index] == stamp) {
                    cal.set(index, field[MAX_FIELD + index]);
                    break;
                }
            }
        }
于是问题出现了,有的线程clear(),有的线程getTime(),这不是搞事情嘛!

三、解决方案

其实也算不上什么解决方案了,既然问题定位到了,那解决办法自然简单,每个线程使用的对象隔离开就搞定了。

1、每个线程创建一个新的SimpleDateFormat对象,也是最简单的,但这样每次都要new对象,让人感觉很不爽抓狂

 

    /**
     * 字符串转化为Date
     * @param date
     * @return
     * @throws ParseException
     */
    public static Date parse(String date) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.parse(date);
    }

2、使用ThreadLocal为每个线程创建一个副本使其隔离,简单的来个饿汉方式搞定吧(毕竟我不是处女座吐舌头)

    /**
     * API的格式
     */
    private static ThreadLocal<SimpleDateFormat> yyyymmdd = new ThreadLocal<SimpleDateFormat>(){
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd");
        }
    };

四、总结

自己用的工具,一定要清楚其原理,否则一失...可就万无啊哭

猜你喜欢

转载自mahl1990.iteye.com/blog/2344958