SimpleDateformat 线程不安全
SimpleDateFormat 继承自 DateFormat, SimpleDateFormat中的parse方法override父类DateFormat的parse方法。DateFormat的父类提供了public setCalendar的方法 导致潜在的线程安全问题。
- parse方法不安全,使用了实例变量calendar. 当SimpleDateFormat设置为静态变量,多线程calendar发生变化,造成parse中的calendar变量发生了修改。

- format方法不安全,同样是calendar引起的。

解决方案一 jdk7 ThreadLocal
public class MyDateUtil { private static final ThreadLocal<DateFormat> threadSafeFormat = new ThreadLocal<DateFormat>(); private static final String MESSAGE_FORMAT = "MM-dd

SimpleDateformat在多线程环境下存在线程安全问题,由于其内部的calendar变量导致parse和format方法不安全。解决方案包括使用JDK7的ThreadLocal或每次新建SimpleDateFormat对象,以及JDK8的DateTimeFormatter,后者为线程安全。
最低0.47元/天 解锁文章
2万+

被折叠的 条评论
为什么被折叠?



