Thread synchronization issues when using SimpleDateFormat. . .

wrong usage:

 public static final SimpleDateFormat DAY_UI_MONTH_DAY_FORMAT = new SimpleDateFormat("MM-dd");
 public static final SimpleDateFormat WEEK_FORMAT = new SimpleDateFormat("EEE", Locale.US);

Ali programming specification tips:

SimpleDateFormat is a thread-unsafe class. Generally, it should not be defined as a static variable. If it is defined as static, it must be locked, or the DateUtils tool class should be used. 
Note: If it is an application of JDK8, you can use instant instead of Date, LocalDateTime instead of Calendar, and DateTimeFormatter instead of SimpleDateFormat.
The official explanation is: simple beautiful strong immutable thread- safe. Positive example 1private static final String FORMAT = "yyyy-MM-dd HH:mm:ss"; public String getFormat(Date date){ SimpleDateFormat dateFormat = new SimpleDateFormat(FORMAT); return sdf.format(date); } Positive example 2private static final SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); public void getFormat(){ synchronized (sdf){ sdf.format(new Date()); ….; } Positive example 3private static final ThreadLocal<DateFormat> DATE_FORMATTER = new ThreadLocal<DateFormat>() { @Override protected DateFormat initialValue() { return new SimpleDateFormat("yyyy-MM-dd"); } };

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325222825&siteId=291194637