In java projects, we usually write a dateutil class to process the conversion of dates and strings. As follows:
Public class dateutil {
Private static simpledateformat sdf = new simpledateformat ("yyyymmdd ");
Public static formatdatetoyyyymmddstr (date ){
Return sdf. format (date );
}
Public static formatyyyymmddstrtodate (string str ){
Return sdf. parse (str );
}
}
However, because the simpledateformat class is not thread-safe, unexpected results often occur in a multi-threaded environment.
There are three ways to solve the above problems.
1) create a new simpledateformat instance each time you use it. If this method is not frequently used, you can use this method to reduce the overhead of creating new objects.
2) use synchronization:
Public class dateutil {
Private simpledateformat sdf = new simpledateformat ("yyyymmdd ");
Private date parse (string datestr) throws parseexception {
Synchronized (sdf ){
Return sdf. parse (datestr );
}
}
Private string format (date ){
Synchronized (sdf ){
Return sdf. format (datestr );
}
}
}
However, when there are many threads and a thread calls this method, other threads that want to call this method need to block it. Such operations will also affect the performance to a certain extent.
I personally recommend the third method, that is, using threadlocal object, each thread creates only one instance.
Public class dateutil {
Private static final string date_format = "yyyymmdd ";
@ Suppresswarnings ("rawtypes ")
Private static threadlocal = new threadlocal (){
Protected synchronized object initialvalue (){
Return new simpledateformat (date_format );
}
};
Public static dateformat getdateformat (){
Return (dateformat) threadlocal. get ();
}
Public static date parse (string textdate) throws parseexception {
Return getdateformat (). parse (textdate );
}
}