SimpleDateFormat是JDK中长久以来自带的日期时间格式化类,但是它有线程安全性方面的问题,使用时要避免它带来的影响。
SimpleDateFormat是线程不安全的
写一个SimpleDateFormat在并发环境下简单的例子先。
public class SimpleDateFormatExample {
private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static void main(String[] args) {
// 创建线程池,最好直接new ThreadPoolExecutor,而不是用Executors工具类
// ExecutorService threadPool = Executors.newCachedThreadPool();
ExecutorService threadPool = new ThreadPoolExecutor(
5, 50, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(100)
);
List<String> dates = Arrays.asList(
"2019-02-21 15:47:01",
"2018-03-22 16:46:02",
"2017-04-23 17:45:03",
"2016-05-24 18:44:04",
"2015-06-25 19:43:05",
"2014-07-26 20:42:06",
"2013-08-27 21:41:07",
"2012-09-28 22:40:08",
"2011-10-29 23:39:09"
);
for (String date : dates) {
threadPool.execute(() -> {
try {
System.out.println(simpleDateFormat.parse(date));
} catch (ParseException e) {
e.printStackTrace();
}
});
}
}
}
输出非常混乱,抛出大量NumberFormatException,以及得出错误的结果。
Exception in thread "pool-1-thread-2" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Long.parseLong(Long.java:601)
at java.lang.Long.parseLong(Long.java:631)
at java.text.DigitList.getLong(DigitList.java:195)
at java.text.DecimalFormat.parse(DecimalFormat.java:2084)
at java.text.SimpleDateFormat.subParse(SimpleDateFormat.java:1869)
at java.text.SimpleDateFormat.parse(SimpleDateFormat.java:1514)
at java.text.DateFormat.parse(DateFormat.java:364)
at me.lmagics.SimpleDateFormatExample.lambda$main$0(SimpleDateFormatExample.java:42)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Exception in thread "pool-1-thread-4" Exception in thread "pool-1-thread-3" java.lang.NumberFormatException: For input string: ".809E.809E22"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
at java.lang.Double.parseDouble(Double.java:538)
at java.text.DigitList.getDouble(DigitList.java:169)
at java.text.DecimalFormat.parse(DecimalFormat.java:2089)
at java.text.SimpleDateFormat.subParse(SimpleDateFormat.java:1869)
at java.text.SimpleDateFormat.parse(SimpleDateFormat.java:1514)
at java.text.DateFormat.parse(DateFormat.java:364)
at me.lmagics.SimpleDateFormatExample.lambda$main$0(SimpleDateFormatExample.java:42)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
java.lang.NumberFormatException: For input string: ".809E.809E22"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
at java.lang.Double.parseDouble(Double.java:538)
at java.text.DigitList.getDouble(DigitList.java:169)
at java.text.DecimalFormat.parse(DecimalFormat.java:2089)
at java.text.SimpleDateFormat.subParse(SimpleDateFormat.java:1869)
at java.text.SimpleDateFormat.parse(SimpleDateFormat.java:1514)
Wed Mar 23 16:46:02 CST 1
Tue May 24 18:44:04 CST 2016
at java.text.DateFormat.parse(DateFormat.java:364)
Wed Mar 23 16:46:02 CST 1
at me.lmagics.SimpleDateFormatExample.lambda$main$0(SimpleDateFormatExample.java:42)
Thu Feb 21 15:47:01 CST 2019
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
Thu Jun 25 19:43:05 CST 2015
Thu Oct 29 23:39:09 CST 2011
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
然后通过SimpleDateFormat的源码来分析它线程不安全的根本原因。
SimpleDateFormat是继承自DateFormat类,DateFormat类中维护了一个全局的Calendar变量。
/**
* The {@link Calendar} instance used for calculating the date-time fields
* and the instant of time. This field is used for both formatting and
* parsing.
*
* <p>Subclasses should initialize this field to a {@link Calendar}
* appropriate for the {@link Locale} associated with this
* <code>DateFormat</code>.
* @serial
*/
protected Calendar calendar;
从注释可以看出,这个Calendar对象既用于格式化也用于解析日期时间。再查看parse()方法接近最后的部分。
Date parsedDate;
try {
parsedDate = calb.establish(calendar).getTime();
// If the year value is ambiguous,
// then the two-digit year == the default start year
if (ambiguousYear[0]) {
if (parsedDate.before(defaultCenturyStart)) {
parsedDate = calb.addYear(100).establish(calendar).getTime();
}
}
}
// An IllegalArgumentException will be thrown by Calendar.getTime()
// if any fields are out of range, e.g., MONTH == 17.
catch (IllegalArgumentException e) {
...
}
return parsedDate;
可见,最后的返回值是通过调用CalendarBuilder.establish()方法获得的,而它的入参正好就是前面的Calendar对象。
Calendar establish(Calendar cal) {
boolean weekDate = isSet(WEEK_YEAR)
&& field[WEEK_YEAR] > field[YEAR];
if (weekDate && !cal.isWeekDateSupported()) {
// Use YEAR instead
if (!isSet(YEAR)) {
set(YEAR, field[MAX_FIELD + WEEK_YEAR]);
}
weekDate = false;
}
cal.clear();
// Set the fields from the min stamp to the max stamp so that
// the field resolution works in the Calendar.
for (int stamp = MINIMUM_USER_STAMP; stamp < nextStamp; stamp++) {
for (int index = 0; index <= maxFieldIndex; index++) {
if (field[index] == stamp) {
cal.set(index, field[MAX_FIELD + index]);
break;
}
}
}
if (weekDate) {
int weekOfYear = isSet(WEEK_OF_YEAR) ? field[MAX_FIELD + WEEK_OF_YEAR] : 1;
int dayOfWeek = isSet(DAY_OF_WEEK) ?
field[MAX_FIELD + DAY_OF_WEEK] : cal.getFirstDayOfWeek();
if (!isValidDayOfWeek(dayOfWeek) && cal.isLenient()) {
if (dayOfWeek >= 8) {
dayOfWeek--;
weekOfYear += dayOfWeek / 7;
dayOfWeek = (dayOfWeek % 7) + 1;
} else {
while (dayOfWeek <= 0) {
dayOfWeek += 7;
weekOfYear--;
}
}
dayOfWeek = toCalendarDayOfWeek(dayOfWeek);
}
cal.setWeekDate(field[MAX_FIELD + WEEK_YEAR], weekOfYear, dayOfWeek);
}
return cal;
}
该方法中先后调用了cal.clear()与cal.set(),也就是先清除cal对象中设置的值,再重新设置新的值。由于Calendar内部并没有线程安全机制,并且这两个操作也都不是原子性的,所以当多个线程同时操作一个SimpleDateFormat时就会引起cal的值混乱。类似地,format()方法也存在同样的问题。
为什么用ThreadLocal能解决问题
ThreadLocal即线程本地变量。它用来为每个线程维护一个专属的变量副本,线程对自己的变量副本进行操作时,对其他线程的变量副本没有任何影响。由此可见,它特别适合解决并发情况下变量共享造成的线程安全性问题,前提是各个副本隔离后不影响业务运行。
以上面的SimpleDateFormat问题为例,ThreadLocal可以这样使用。
// 可以直接设置初始值
private static ThreadLocal<SimpleDateFormat> simpleDateFormat = ThreadLocal.withInitial(() ->
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
);
// 也可以调用set()方法
private static ThreadLocal<SimpleDateFormat> simpleDateFormat = new ThreadLocal<>();
simpleDateFormat.set(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
...
// 调用get()方法取得值
System.out.println(simpleDateFormat.get().parse(date));
// 移除
simpleDateFormat.remove();
那么ThreadLocal是采用了什么机制来实现变量副本隔离的呢?在Thread类内部,有如下的定义。
/* ThreadLocal values pertaining to this thread. This map is maintained
* by the ThreadLocal class. */
ThreadLocal.ThreadLocalMap threadLocals = null;
可见每个线程都维护了一个叫ThreadLocalMap的东西,它是ThreadLocal中定义的一个静态内部类。其实现类似于HashMap,但没实现Map接口,数据结构和内部逻辑也有不同。ThreadLocalMap.Entry是这样定义的。
static class Entry extends WeakReference<ThreadLocal<?>> {
/** The value associated with this ThreadLocal. */
Object value;
Entry(ThreadLocal<?> k, Object v) {
super(k);
value = v;
}
}
该Entry的键值类型都是确定的。值就是变量的副本,键是对ThreadLocal对象的一个弱引用。由于线程并不能直接访问和存取ThreadLocalMap,只能藉由ThreadLocal进行,因此不同的线程之间的变量副本就实现了隔离。
上面的图来自阿里Java开发手册,清晰地示出了线程、ThreadLocal、ThreadLocalMap三者的引用关系,鼓掌。
另外,ThreadLocal还可能存在内存泄漏的问题,前人已经写过很好的分析文章,如https://www.jianshu.com/p/a1cd61fa22da,下面稍作总结。
-
回忆Java中的4种引用类型:强、软、弱、虚引用,其引用强度依次递减。其中弱引用只能存活到下一次Young GC发生之前。
- ThreadLocalMap.Entry中的键就是弱引用,如果它被回收,会出现key为null但value仍然存在的情况(value是强引用,当然Entry也没有被回收),有内存泄漏风险。ThreadLocal的设计者已经考虑到了这种情况,调用get()/set()/remove()方法时,都会调用expungeStaleEntry()方法来删除这种key已经被回收了的Entry。这段代码很有意思,关键点添加了一点注释。
private int expungeStaleEntry(int staleSlot) {
Entry[] tab = table;
int len = tab.length;
// expunge entry at staleSlot
// 将值和Entry都设成null,这样在下一次GC根搜索时均不可达,就被回收了
tab[staleSlot].value = null;
tab[staleSlot] = null;
size--;
// Rehash until we encounter null
// 还没完,接下来会继续找key为null的其他Entry,一起删掉
Entry e;
int i;
for (i = nextIndex(staleSlot, len);
(e = tab[i]) != null;
i = nextIndex(i, len)) {
ThreadLocal<?> k = e.get();
if (k == null) {
// 找到了,将值和Entry都设成null
e.value = null;
tab[i] = null;
size--;
} else {
int h = k.threadLocalHashCode & (len - 1);
if (h != i) {
tab[i] = null;
// Unlike Knuth 6.4 Algorithm R, we must scan until
// null because multiple entries could have been stale.
// nextIndex()方法就是(i + 1)%len,ThreadLocalMap是采用线性探测开放定址解决hash冲突的
// 这比HashMap的链地址法(数组+链表)简单得多
while (tab[h] != null)
h = nextIndex(h, len);
tab[h] = e;
}
}
}
return i;
}
- 但是就算这样设计了,也不能完全防止ThreadLocal内存泄漏,因为它可以是static的,也有可能在分配了变量副本之后没调用任何方法。另外,由于ThreadLocalMap的生命周期和线程一样长,因此不管Entry的键是对ThreadLocal的强引用还是弱引用,都有可能出现ThreadLocal被回收变成null的情况。
- 所以,完全避免内存泄漏的唯一手段就是在ThreadLocal用完后,调用remove()方法。
网友评论