1.SimpleDateFormat非线程安全
使用SimpleDateFormat做成员变量被调用时可能会出现线程安全问题,他继承了DateFormat,因为其内部做时间转换用到的Calendar是一个成员变量,会被多个线程共享,调用format函数式执行calendar.setTime(date)很可能改变其他线程的时间,出现时间不对,线程挂死等等
2.优化方案
2.1 每次使用时都构造新对象放在局部变量中使用
2.2 使用ThreadLocal
用ThreadLocal来实现线程缓存,每个线程都有一个独享对象,避免了频繁创建对象,也避免了多线程的竞 争
2.3 Synchronized,不推荐
2.4 FastDateFormat是apache commons包的实现
FastDateFormat通过ConcurrentHashMap,避免所有相关操作线程都存放SimpleDateFormat对象,内存浪费。Map的key是MultipartKey对象(必须实现equals、hashcode方法),value是SimpleDateFormat
3.替代方案
3.1 基于JDK1.8的DateTimeFormatter
这需要对老的DateUtil类重新封装,1.8中推荐的时间类时LocalDateTime,需要和Date做转换
