Skip to content

Commit 20eea55

Browse files
committed
解决多线程下SimpleDateFormat线程不安全造成的bug
1 parent 294b830 commit 20eea55

File tree

1 file changed

+16
-6
lines changed

1 file changed

+16
-6
lines changed

src/main/java/cn/jiguang/common/utils/TimeUtils.java

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,17 +6,27 @@
66

77
public class TimeUtils {
88

9-
private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
10-
private static final SimpleDateFormat TIME_ONLY_FORMAT = new SimpleDateFormat("HH:mm:ss");
9+
private static final ThreadLocal<SimpleDateFormat> DATE_FORMAT = new ThreadLocal<SimpleDateFormat>() {
10+
@Override
11+
protected SimpleDateFormat initialValue() {
12+
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
13+
}
14+
};
15+
private static final ThreadLocal<SimpleDateFormat> TIME_ONLY_FORMAT = new ThreadLocal<SimpleDateFormat>() {
16+
@Override
17+
protected SimpleDateFormat initialValue() {
18+
return new SimpleDateFormat("HH:mm:ss");
19+
}
20+
};
1121

1222
static {
13-
DATE_FORMAT.setLenient(false);
14-
TIME_ONLY_FORMAT.setLenient(false);
23+
DATE_FORMAT.get().setLenient(false);
24+
TIME_ONLY_FORMAT.get().setLenient(false);
1525
}
1626

1727
public static boolean isDateFormat(String time) {
1828
try {
19-
DATE_FORMAT.parse(time);
29+
DATE_FORMAT.get().parse(time);
2030
} catch (ParseException e) {
2131
return false;
2232
}
@@ -25,7 +35,7 @@ public static boolean isDateFormat(String time) {
2535

2636
public static boolean isTimeFormat(String time) {
2737
try{
28-
TIME_ONLY_FORMAT.parse(time);
38+
TIME_ONLY_FORMAT.get().parse(time);
2939
} catch (ParseException e) {
3040
return false;
3141
}

0 commit comments

Comments
 (0)