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