SimpleDateFormat线程安全问题

今天线上出现了问题,从第三方获取的日期为 2019-12-12 11:11:11,通过SimpleDateFormat转换格式后,竟然出现完全不正常的日期数据,经百度,得知SimpleDateFormat为线程不安全的

表现为有时报错 java.lang.NumberFormatException

有时传入的日期,转换结果不对

总结:创建日期工具类时,不要将 SimpleDateFormat 定义为 公共变量,如果定义为公共变量,需要加锁

其他解决方案(阿里手册):

1、使用 org.apache.commons.lang3.time.DateUtils (他是通过Calendar实现的)

2、  ThreadLocal使用完后必须通过try...finally...对ThreadLocal进行回收

private static final ThreadLocal<DateFormat> df = new ThreadLocal<DateFormat>() {
  @ Override
  protected DateFormat initialValue() {
    return new SimpleDateFormat("yyyy-MM-dd");
  }
};

3、java8中,使用 Instant、LocalDateTime、DateTimeFormatter 

原文地址:https://www.cnblogs.com/jaxlove-it/p/11233278.html