Java SimpleDateFormat 线程不安全问题解决

2019-11-26  本文已影响0人  旋涡_宫城

SimpleDateFormat 日常编码中经常使用的一个日期格式化的工具类,可以使用它将日期与字符串之间随意的转换。

        // 将一个字符串转换为日期格式
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date date = format.parse("2019-11-25");
        // 将一个日期转为字符串
        Date date1 = new Date();
        String date12Str = format.format(date1);

多个线程情况下,多执行几次,会出现解析错误。

    public static void main(String[] args) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

        // 10个线程,将10个日期字符串使用SimpleDateFormat转为Date
        for (int i = 0; i < 10; i++) {
            String str = "2019-11-0"+i;
            new Thread(()->{
                try {
                    System.out.println(format.parse(str));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
//错误日志
Exception in thread "Thread-0" java.lang.NumberFormatException: For input string: ""
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Long.parseLong(Long.java:601)
    at java.lang.Long.parseLong(Long.java:631)
    at java.text.DigitList.getLong(DigitList.java:195)
    at java.text.DecimalFormat.parse(DecimalFormat.java:2084)
    at java.text.SimpleDateFormat.subParse(SimpleDateFormat.java:1869)
    at java.text.SimpleDateFormat.parse(SimpleDateFormat.java:1514)
    at java.text.DateFormat.parse(DateFormat.java:364)
    at com.hd.test.SdfDemo.lambda$main$0(SdfDemo.java:27)
    at java.lang.Thread.run(Thread.java:748)
Sun Nov 03 00:00:00 CST 2019
Fri Nov 01 00:00:00 CST 2019

查看类图如下:


image.png

从SimpleDateFormat ,parse()方法查看,这里面有一个Calendar对象,将字符串对象放入Calendar中,Calendar有一个清理的方法Clear(),这里不是原子操作,线程不安全的。
当多个线程执行时,线程A清理了线程B的Calendar对象,造成了程序的错误。

    public Date parse(String text, ParsePosition pos)
    {
       
        //(1)解析日期字符串放入CalendarBuilder的实例calb中
        .....

        Date parsedDate;
        try {//(2)使用calb中解析好的日期数据设置calendar
            parsedDate = calb.establish(calendar).getTime();
            ...
        }
       
        catch (IllegalArgumentException e) {
           ...
            return null;
        }

        return parsedDate;
    }

   Calendar establish(Calendar cal) {
   ...
   //(3)重置日期对象cal的属性值
   cal.clear();
   //(4) 使用calb中中属性设置cal
   ...
   //(5)返回设置好的cal对象
   return cal;
   }


    public final void clear()
   {
       for (int i = 0; i < fields.length; ) {
           stamp[i] = fields[i] = 0; // UNSET == 0
           isSet[i++] = false;
       }
       areAllFieldsSet = areFieldsSet = false;
       isTimeSet = false;
   }

有什么解决的方法呢:

  1. 第一个想到的就是每个线程自己new 自己的simpleDateFormat.
    这种用完即走,开销比较大
    2.第二个增加同步synchronized,多线程情况下需要竞争锁,并发场景下性能下降
    3.使用ThreadLocal,这种方式不需要每次都new,也不需要竞争锁,实在是高效,完美。
/**
 * 描述:  SimpleDateFormat 线程安全问题
 * @author hd
 * @date 2019-11-26 11:25
 **/
public class SdfDemo {
    private final  static ThreadLocal<DateFormat> tl = new ThreadLocal<DateFormat>(){
        @Override
        protected SimpleDateFormat initialValue(){
            return new SimpleDateFormat("yyyy-MM-dd");
        }
    };
    public static void main(String[] args) {

        // 10个线程,将10个日期字符串使用SimpleDateFormat转为Date
        for (int i = 0; i < 10; i++) {
            String str = "2019-11-0"+i;
            new Thread(()->{
                try {
                    System.out.println(tl.get().parse(str)+" 对象:"+tl.get());
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}

// 日志,可以看到SimpleDateFormat 是使用的同一个对象
Mon Nov 04 00:00:00 CST 2019 对象:java.text.SimpleDateFormat@f67a0200
Thu Oct 31 00:00:00 CST 2019 对象:java.text.SimpleDateFormat@f67a0200
Thu Nov 07 00:00:00 CST 2019 对象:java.text.SimpleDateFormat@f67a0200
Sun Nov 03 00:00:00 CST 2019 对象:java.text.SimpleDateFormat@f67a0200
Tue Nov 05 00:00:00 CST 2019 对象:java.text.SimpleDateFormat@f67a0200
Sat Nov 02 00:00:00 CST 2019 对象:java.text.SimpleDateFormat@f67a0200
Wed Nov 06 00:00:00 CST 2019 对象:java.text.SimpleDateFormat@f67a0200
Sat Nov 09 00:00:00 CST 2019 对象:java.text.SimpleDateFormat@f67a0200
Fri Nov 08 00:00:00 CST 2019 对象:java.text.SimpleDateFormat@f67a0200
Fri Nov 01 00:00:00 CST 2019 对象:java.text.SimpleDateFormat@f67a0200

都是一些日常总结,

如果您觉得有帮助的话,记得 评论,关注,转发,收藏,双击么么哒。


上一篇 下一篇

猜你喜欢

热点阅读