SimpleDateFormat thread Security Solution

Source: Internet
Author: User
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 );
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.