Java Multithreading: SimpleDateFormat

Source: Internet
Author: User

One, SimpleDateFormat thread-safety issues

Why is SimpleDateFormat thread unsafe?

The following is a case code to illustrate
 Public classDateutiltest { Public Static classTestsimpledateformatthreadsafeextendsThread {@Override Public voidrun () { while(true) {                Try {                     This. Join (2000); } Catch(interruptedexception E1) {e1.printstacktrace (); }                Try{System.out.println ( This. GetName () + ":" +dateutil.parse ("2013-05-24 06:02:20")); } Catch(ParseException e) {e.printstacktrace (); }            }        }        }             Public Static voidMain (string[] args) { for(inti = 0; I < 3; i++){            NewTestsimpledateformatthreadsafe (). Start (); }                }}

The execution output is as follows:

Exception in thread "Thread-1"java.lang.NumberFormatException:multiple points at sun.misc.FloatingDecimal.readJavaFormatString ( Floatingdecimal.java:1082) at java.lang.Double.parseDouble (Double.java:510) at java.text.DigitList.getDouble (Digitlist.java:151) at Java.text.DecimalFormat.parse (Decimalformat.java:120S) at Java.text.SimpleDateFormat.subParse (Simpledateformat.java:1589) at Java.text.SimpleDateFormat.parse (Simpledateformat.java:1311) at Java.text.DateFormat.parse (Dateformat.java:335) at Com.peidasoft.orm.dateformat.DateNoStaticUtil.parse (Datenostaticutil.java:17) at Com.peidasoft.orm.dateformat.dateutiltest$testsimpledateformatthreadsafe.run (DateUtilTest.java:20) Exception in thread"Thread-0"java.lang.NumberFormatException:multiple points at sun.misc.FloatingDecimal.readJavaFormatString ( Floatingdecimal.java:1082) at java.lang.Double.parseDouble (Double.java:510) at java.text.DigitList.getDouble (Digitlist.java:151) at Java.text.DecimalFormat.parse (Decimalformat.java:1302) at Java.text.SimpleDateFormat.subParse (Simpledateformat.java:1589) at Java.text.SimpleDateFormat.parse (Simpledateformat.java:1311) at Java.text.DateFormat.parse (Dateformat.java:335) at Com.peidasoft.orm.dateformat.DateNoStaticUtil.parse (Datenostaticutil.java:17) at Com.peidasoft.orm.dateformat.dateutiltest$testsimpledateformatthreadsafe.run (DateUtilTest.java:20) Thread-2:mon 06:02:20 CST 2021Thread-2:fri 06:02:20 CST 2013

Description: Thread-1 and Thread-0 reported java.lang.NumberFormatException:multiple points error, directly hanging dead, not up; Thread-2 although not dead, but the output time is wrong, For example, we entered the time is: 2017-05-24 06:02:20, when the output: Mon may 06:02:20 CST 2021 such a supernatural event

two. Causes

As a professional programmer, we all know that the overhead of sharing a variable is much smaller than creating a new variable every time. The above optimized static version of SimpleDateFormat, where there are various supernatural errors in the concurrency situation, is because the SimpleDateFormat and DateFormat classes are not thread-safe. The reason we ignore thread safety is because the interfaces that SimpleDateFormat and DateFormat provide to us do not show how it is related to thread safety. Just at the bottom of the JDK documentation is the following description:

The date format in SimpleDateFormat is not synchronized. It is recommended (recommended) to create a separate format instance for each thread. If multiple threads access a format at the same time, it must remain externally synchronized.

The JDK original document is as follows:
Synchronization:
Date formats is not synchronized.
It is recommended to the create separate format instances for each thread.
If Multiple threads access a format concurrently, it must be synchronized externally.

Let's look at the JDK source code to see why the SimpleDateFormat and DateFormat classes are not the real reason for thread safety:

SimpleDateFormat inherits DateFormat, which defines the object of the Calendar class for a protected attribute in DateFormat: Calendar. Just because the calendar tired concept complex, involved in time zone and localization and so on, the JDK implementation of the use of member variables to pass parameters, which results in a multi-threaded error occurs.

In the format method, there is a code like this:

Privatestringbuffer Format (date date, StringBuffer toappendto, Fielddelegate delegate) { //Convert Input Date to TIME field listcalendar.settime (date); BooleanUsedateformatsymbols =Usedateformatsymbols ();  for(inti = 0; I <compiledpattern.length;) {            intTag = Compiledpattern[i] >>> 8; intCount = compiledpattern[i++] & 0xff; if(Count = = 255) {Count= compiledpattern[i++] << 16; Count|= compiledpattern[i++]; }Switch(tag) { CaseTAG_QUOTE_ASCII_CHAR:toAppendTo.append ((Char) count);  Break;  CaseTAG_QUOTE_CHARS:toAppendTo.append (Compiledpattern, I, count); I+=count;  Break; default: Subformat (Tag, count, delegate, Toappendto, Usedateformatsymbols);  Break; }}returntoappendto; }

Calendar.settime (date) This statement changes the calendar, and later, the calendar is used (in the Subformat method), which is the root cause of the problem. Imagine that in a multithreaded environment, two threads hold an instance of the same simpledateformat, calling the Format method, respectively:
thread 1 calls the Format method, which changes the Calendar field.
the interruption came.
thread 2 starts execution and it also changes the calendar.
was interrupted again.
Thread 1 comes back, and at this point, the calendar is not the value it set, but the path of thread 2 design. If more than one thread competes for the Calendar object at the same time, there are various problems, such as incorrect timing, thread hangs, and so on.
analysis of the implementation of format, we are not difficult to find that the use of member variables calendar, the only advantage is that when the call Subformat, the lack of a parameter, but brought many of these problems. In fact, as long as here with a local variable, all the way down, all the problems will be solved.
There is a more important problem behind this question-stateless: one of the benefits of a stateless approach is that it can be safely invoked in a variety of environments. To measure whether a method is stateful, see if it changes something else, such as a global variable, such as an instance field. The Format method changes the Calendar field of the SimpleDateFormat during the run, so it is stateful.

This also reminds us to note the next three points when developing and designing the system:

1. When you write a common class, make a clear explanation of the consequences of the multi-threaded call case in the comments

2. Be aware of thread safety for each shared mutable variable in a threaded environment

3. Our classes and methods are designed to be as stateless as possible.

three. Workaround

1. Using synchronization

 Public classDatesyncutil {Private StaticSimpleDateFormat SDF =NewSimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");  Public StaticString formatdate (date date)throwsparseexception{synchronized(SDF) {returnSdf.format (date); }      }         Public StaticDate Parse (String strdate)throwsparseexception{synchronized(SDF) {returnSdf.parse (strdate); }    } }

Note: When a thread calls this method when a thread is many, other threads that want to call this method will block, and multithreading concurrency can have a certain effect on performance.

2. Using threadlocal

 Public classDateutilsextendsOrg.apache.commons.lang3.time.DateUtils { Public Static FinalString pattern_date_time = "Yyyy-mm-dd HH:mm:ss"; Private  StaticMap<string, threadlocal<dateformat>>Dateformatmap; /*** Create a singleton * without using singleton mode, Spring will call GetDateFormat (pattern) when it injects data, because Dateformatmap is not initialized Nullpoint *@return     */    Private StaticMap<string, threadlocal<dateformat>>Getdateformatmap () {if(Dateformatmap = =NULL) {            synchronized(Dateutils.class) {                if(Dateformatmap = =NULL) {Dateformatmap=NewConcurrenthashmap<>(); }            }        }        returnDateformatmap; }        /*** Get thread-safe DateFormat * SimpleDateFormat has two problems: * 1. Non-thread-safe, simply declared as static, not locked in use when calling Parse () in a concurrency condition may get the wrong time * 2. Frequent instantiation may cause memory overflow * Use threadlocal to turn DateFormat into thread-exclusive, both to avoid concurrency problems and to reduce the overhead of repeatedly creating instances *@paramPattern *@return     */     Public  StaticDateFormat GetDateFormat (FinalString pattern) {ThreadLocal<DateFormat> DateFormat =Getdateformatmap (). get (pattern); if(DateFormat = =NULL) {DateFormat=NewThreadlocal<dateformat>() {@OverrideprotectedDateFormat InitialValue () {return NewSimpleDateFormat (pattern);            }            };        Dateformatmap.put (pattern, dateformat); }        returnDateformat.get (); }    /*** Date format "YYYY-MM-DD HH:mm:ss" String * *@paramDate *@return     */     Public StaticString dateformattostring (date date) {DateFormat SDF=GetDateFormat (pattern_date_time); returnSdf.format (date); }}

Description: Using threadlocal, the shared variable is also changed to exclusive, the thread exclusive can be compared to the method exclusive in the concurrency environment can reduce the cost of many objects created. This approach is generally recommended if performance requirements are high.

3. Discard the JDK and use time formatting classes from other class libraries

1. Using Apache Commons Fastdateformat, claiming to be both fast and thread-safe simpledateformat, unfortunately it can only format the date, cannot parse the date string.

2. Use the Joda-time class library to handle time-related issues

Resources:

  In-depth understanding of Java:simpledateformat security time formatting

SimpleDateFormat Thread safety problems and threadlocal

Java Multithreading: SimpleDateFormat

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.