1. Causes of thread safety problems
Thread safety issues are caused by global variables and static variables.
2. Thread safety issues
SimpleDateFormate sdf = new SimpleDateFormat(); Use sdf.parse(dateStr); sdf.format(date); There is a reference to the Caleadar object in sdf.parse(dateStr); in the source code, calendar.clear(); and calendar.getTime(); // Get the time of calendar
If thread A calls sdf.parse() and has not yet executed calendar.getTime() after calendar.clear(), thread B calls sdf.parse() again, then thread B also executes the sdf.clear() method, which causes thread A's calendar data to be cleared;
ThreadLocal uses space to exchange time, synchronized uses time to exchange space
Use ThreadLocal to solve thread safety:
public class ThreadLocalDateUtil { private static final String date_format = "yyyy-MM-dd HH:mm:ss"; private static ThreadLocal<DateFormat> threadLocal = new ThreadLocal<DateFormat>(); public static DateFormat getDateFormat() { DateFormat df = threadLocal.get(); if(df==null){ df = new SimpleDateFormat(date_format); threadLocal.set(df); } return df; } public static String formatDate(Date date) throws ParseException { return getDateFormat().format(date); } public static Date parse(String strDate) throws ParseException { return getDateFormat().parse(strDate); } }Using synchronized solution:
public class DateSyncUtil { private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); public static String formatDate(Date date)throws ParseException{ synchronized(sdf){ return sdf.format(date); } } public static Date parse(String strDate) throws ParseException{ synchronized(sdf){ return sdf.parse(strDate); } }}Thank you for reading this article, I hope it can help you. Thank you for your support for this website!