Using threadlocal to solve the problem of Simpladateformat thread insecurity

Source: Internet
Author: User
Tags string format

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

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.