[Technology Sharing]20180109_ Multithreading _ threadlocal Addressing thread safety issues (JDK 1.7)

Source: Internet
Author: User
Tags dateformat

There is a thread safety issue below:

 Public classTestsimpledateformat { Public Static voidMain (string[] args)throwsinterruptedexception, executionexception {//SimpleDateFormat sdf = new SimpleDateFormat ("YyyyMMdd");DateTimeFormatter DTF= Datetimeformatter.ofpattern ("YyyyMMdd");//Java 8 availablecallable<LocalDate> task =NewCallable<localdate>() {@Override PublicLocaldate Call ()throwsException {returnLocaldate.parse ("20180109", DTF);//Java 8 available//return Dateformatthreadlocal.convert ("20180109");            }                    }; List<Future<LocalDate>> list =NewArraylist<>(); Executorservice Pool= Executors.newfixedthreadpool (10);  for(inti=0;i<10;i++) {List.add (Pool.submit (Task)); }                 for(future<localdate>future:list)        {System.out.println (Future.get ()); } pool.shutdown ();    //Remember to close } }

Here is the Threadlocal class:

public class Dateformatthreadlocal {        private static final threadlocal<dateformat> tl = new threadlocal< Dateformat> () {                protected DateFormat InitialValue () {            return new SimpleDateFormat ("YyyyMMdd");        }            }; Public        static final Date convert (String source) throws parseexception{        return Tl.get (). Parse (source);}    }

[Technology Sharing]20180109_ Multithreading _ threadlocal Addressing thread safety issues (JDK 1.7)

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.