DateFormat of the format () method thread unsafe problem analysis

Source: Internet
Author: User
Tags dateformat

Recently saw "Detective Theater: Heap Memory Mysterious Overflow event" https://my.oschina.net/u/2368090/blog/1628720, so I also want to test to understand dateformat multithreading security issues.

First look at the phenomenon: do a multithreaded use of the same Simplydateformat test example:

Import Java.text.simpledateformat;import Java.util.date;public class Dateformattest {    static SimpleDateFormat SDF = new SimpleDateFormat ("Yyyy-mm-dd");    public static void Main (string[] args) throws exception{        Date start = Sdf.parse ("2018-03-01");        Date end = Sdf.parse ("2018-03-03");        Final Date other =sdf.parse ("2018-03-07");        for (int i=0, i<100; i++) {            new Thread (new Runnable () {public                void run () {                    sdf.format (other);                }            } ). Start ();        }        System.out.println ("Start:" + Sdf.format (start));        System.out.println ("End:" + sdf.format (end));}    }

(This code in the virtual function quickly reproduce the problem, on the Mac to quickly and continuously click on the run will be reproduced--)

Expected Result:

The results of thread safety occur:

After reading the phenomenon to find the reason:

1.DateFormat (parent Class) defines a global calendar:

The Simplydateformat format () method uses the global calendar in the case of unsafe threads:

The approximate order in which the problem is generated may be this:

DateFormat of the format () method thread unsafe problem analysis

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.