The reason why thread-safety problems arise
Thread safety problems are caused by global variables and static variables.
Ii. Thread-safety issues
Simpledateformate SDF = new SimpleDateFormat (); use Sdf.parse (DATESTR); Sdf.format (date); There is a reference to the Caleadar object within the SDF. In the source code sdf.parse (DATESTR); Calendar.clear (); and Calendar.gettime (); Time to get calendar
If thread A calls Sdf.parse () and Calendar.clear () has not executed calendar.gettime (), then thread B calls Sdf.parse (), and thread B executes the Sdf.clear () method , which causes the calendar data for thread A to be emptied;
Threadlocal is to use space to change time, synchronized is to use time to change space
Using threadlocal to resolve 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 the 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 to help you, thank you for your support for this site!