SimpleDateFormat多线程问题
四月份在优化一个功能时候,尝试把Date和SimpleDateFormat封装在class中,然后统一format和parse解析,以此避免重复new对象节省重复申请内存。于是就遇到了一个坑——经常出现莫名其妙的日期,打印出来时候甚至有0650年的日期,唐朝啊,难道计算机给我玩穿越?!,大家都知道一般日期是1970-01-01开始的,要么再早一些事1900-01-01开始的,不会再早了。
一开始怀疑事输入问题造成的,但是经过一番调试发现传入数据没错,传入数据在经过统一对象Format和parse后就出现日期不对,怀疑是SimpleDateFormat的问题。于是查阅官方文档
https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
文档最后特定对多线程做如下描述
Synchronization
Date formats are not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally.
官方文档说的明明白白,SimpleDateFormat不是线程安全的,如果需要多线程使用,那么需要显示synchronized同步。
首先定义日志打印类
private void log(String message) {
StackTraceElement[] elements = Thread.currentThread().getStackTrace();
android.util.Log.d(TAG, elements[5].getMethodName() + "() " + message);
}
在没有加锁时的例子
@Test
public void multiThreadTest() {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
final long timeMillSec = Calendar.getInstance().getTimeInMillis();
List<Thread> threadList = new ArrayList<>();
for (int i = 0; i < 20; i++) {
Thread t = new Thread(new DateFormatTask(dateFormat, timeMillSec));
t.setName("thread-" + i);
t.start();
threadList.add(t);
}
try {
Thread.sleep(3000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* SimpleDateFormat测试,没有加锁版本
*/
private class DateFormatTask implements Runnable {
private DateFormat dateFormat;
private long timeMillSec = 0;
private DateFormatTask(DateFormat dateFormat, long timeMillSec) {
this.dateFormat = dateFormat;
this.timeMillSec = timeMillSec;
}
@Override
public void run() {
String dateText = dateFormat.format(new Date(timeMillSec));
long parseTimeMillSec = 0L;
try {
parseTimeMillSec = dateFormat.parse(dateText).getTime();
String newDateText = dateFormat.format(new Date(parseTimeMillSec));
log(Thread.currentThread().getName() + " timeMillSec: " + timeMillSec
+ ", dateText: " + dateText
+ ", parseTimeMillSec: " + parseTimeMillSec
+ ", newDateText: " + newDateText);
} catch (ParseException e) {
log(Thread.currentThread().getName() + ", parse failed. "
+ e.getClass().getSimpleName() + " " + e.getMessage()
+ " timeMillSec: " + timeMillSec);
} catch (Exception e) {
log(Thread.currentThread().getName() + ", parse failed. "
+ e.getClass().getSimpleName() + " " + e.getMessage()
+ " timeMillSec: " + timeMillSec);
}
}
}
输出结果
05-04 22:28:21.871 3337 34