多线程条件下使用SimpleDateFormat报错:java.lang.NumberFormatException: multiple points、empty String、For input

错误详情

       使用时间格式转换SimpleDateFormat方法的时候,用static修饰,并在处于多线程的情况下执行,结果出现各种报错信息

  public static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    public static  Date parse(String stringDate) throws ParseException {
        return sdf.parse(stringDate);
    }

报错信息一

Exception in thread "1" Exception in thread "0" java.lang.NumberFormatException: multiple points
java.lang.NumberFormatException: multiple points

报错信息二

Exception in thread "0" Exception in thread "2" Exception in thread "1" java.lang.NumberFormatException: For input string: "255.E2552E"

java.lang.NumberFormatException: empty String

错误分析 

      SimpleDateFormat类内部有一个Calendar对象引用,它用来储存和这个SimpleDateFormat相关的日期信息,例如sdf.parse(dateStr),sdf.format(date) 诸如此类的方法参数传入的日期相关String,Date等等, 都是交由Calendar引用来储存的.这样就会导致一个问题如果你的SimpleDateFormat是个static的, 那么多个thread 之间就会共享这个SimpleDateFormat, 同时也是共享这个Calendar引用。 SimpleDateFormat 是线程不安全的类,一般不要定义为 static 变量,如果定义为 static,必须加锁,或者使用 DateUtils 工具类。

解决方法

方法1:加锁 (但是性能不太好,不推荐)

  public static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


   public static synchronized Date parse02(String stringDate) throws ParseException {
        return sdf.parse(stringDate);
    }

方法2:ThreadLocal(为每个线程创建独立的格式实例,推荐)记得使用后remove

public static final ThreadLocal<SimpleDateFormat> sdfThreadLocal = ThreadLocal.withInitial(()->new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
    public static Date parseThreadLocal(String stringDate) throws ParseException {
        return sdfThreadLocal.get().parse(stringDate);
    }

另:阿里Java开发手册中推荐,在jdk8中用DateTimeFormatter 代替 SimpleDateFormat

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值