In recent work, inadvertently using a simpledateformat to convert a datetime string to a Date object, it was found that there was a very unusual time, such as when the time of year was obviously incorrect.
Later on the online view found that the original SimpleDateFormat is not thread-safe caused. Later, Dateutil was rewritten, using threadlocal to achieve thread-safe effects.
Threadlocal object A new line thread is called the first time, the InitialValue method is called, and subsequent threads are processed using the object returned by this method, which is equivalent to having a separate SimpleDateFormat object for each thread, achieving a thread-safe effect.
1 classdateutil{2 Private StaticThreadlocal<simpledateformat> ThreadLocal =NewThreadlocal<simpledateformat>(){3 protectedSimpleDateFormat InitialValue () {4 return NewSimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");5 }6 };7 Public StaticDate Parse (String strtime) {8 Try{9 returnThreadlocal.get (). Parse (strtime);Ten}Catch(ParseException e) { One e.printstacktrace (); A } - return NULL; - } the - Public StaticString Format (date date) { - Try{ - returnthreadlocal.get (). Format (date); +}Catch(Exception e) { - e.printstacktrace (); + } A return NULL; at } - - -}
Using threadlocal to solve the problem of Simpladateformat thread insecurity