Java: SimpleDateFormat secure time formatting

Source: Internet
Author: User

We are certainly familiar with SimpleDateFormat. SimpleDateFormat is a very common class in Java. It is used to parse and format the date string. However, it may be very subtle and difficult to debug if you are not careful with it, because the DateFormat and SimpleDateFormat classes are not thread-safe, Synchronous Code should be used to call the format () and parse () methods in a multi-threaded environment to avoid problems. Next we will learn and understand the SimpleDateFormat class step by step through a specific scenario.

  I. Introduction
We are all good programmers. We all know that we should create as few SimpleDateFormat instances as possible in the program, because it takes a lot of money to create such an instance. In an example of reading database data and exporting it to an excel file, each time you process a time message, you need to create a SimpleDateFormat instance object and then discard it. A large number of objects are created in this way, occupying a large amount of memory and jvm space. The Code is as follows:

    String formatDate(Date date)=  SimpleDateFormat("yyyy-MM-dd HH:mm:ss"  Date parse(String strDate) =  SimpleDateFormat("yyyy-MM-dd HH:mm:ss"

You may say, OK, then I will create a static simpleDateFormat instance and put it in a DateUtil class (as shown below). I will directly use this instance for operations during use, this solves the problem. The improved code is as follows:

     SimpleDateFormat sdf =  SimpleDateFormat("yyyy-MM-dd HH:mm:ss"   String formatDate(Date date)  Date parse(String strDate) 

Of course, this method is really good and will work well most of the time. But when you use it in the production environment for a while, you will find the fact that it is not thread-safe. Under normal testing, there is no problem, but once the load is fixed in the production environment, this problem will come out. Different situations may occur, such as incorrect conversion time, errors, and thread crashes. Let's take a look at the following test cases. Let's talk about the facts:

     SimpleDateFormat sdf =  SimpleDateFormat("yyyy-MM-dd HH:mm:ss"   String formatDate(Date date)  Date parse(String strDate) 
    TestSimpleDateFormatThreadSafe  (.join(2000.getName()+":"+DateUtil.parse("2013-05-24 06:02:20"  ( i = 0; i < 3; i++

The execution output is as follows:

Exception in thread "Thread-1"10825101511302158913113351720"Thread-0"10825101511302158913113351720-2:Mon May 24 06:02:20 CST 2021-2:Fri May 24 06:02:20 CST 2013-2:Fri May 24 06:02:20 CST 2013-2:Fri May 24 06:02:20 CST 2013

Note: The error message "Thread-1" and "Thread-0" is reported. The error message "-2" is not reported, but the output time is incorrect, for example, if the input time is 06:02:20, a strange event like Mon May 24 06:02:20 CST 2021 will be output.

  Ii. Cause

As a professional programmer, we all know that the overhead of sharing a variable is much smaller than that of creating a new variable each time. The static SimpleDateFormat version optimized above has encountered various flexibility errors in the case of concurrency, because the SimpleDateFormat and DateFormat classes are not thread-safe. We ignore the thread security issue because, from the interfaces provided by SimpleDateFormat and DateFormat, we cannot see whether it is related to thread security. The following is a description at the bottom of the JDK document:

  The date format in SimpleDateFormat is not synchronized. We recommend that you create an independent format instance for each thread. If multiple threads access one format at a time, it must maintain external synchronization.

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

Next, let's look at the JDK source code to see why SimpleDateFormat and DateFormat classes are not the real cause of thread security:

SimpleDateFormat inherits DateFormat. In DateFormat, it defines the Calendar Class Object of the protected attribute: calendar ar. The concept of Calendar is complex and involves time zone and localization. in Jdk implementation, member variables are used to pass parameters, which leads to errors during multithreading.

In the format method, there is such a piece of code:

  useDateFormatSymbols = ( i = 0; i < tag = compiledPattern[i] >>> 8 count = compiledPattern[i++] & 0xff (count == 255= compiledPattern[i++] << 16|= compiledPattern[i+++=

This statement changes the calendar. Later, the calendar will be used (in the subFormat method), which is the root cause of the problem. Imagine that in a multi-threaded environment, two threads hold the same SimpleDateFormat instance and call the format method respectively:
Thread 1 calls the format method and changes the calendar field.
Interrupted.
Thread 2 starts to execute, and it also changes the calendar.
Interrupted again.
Thread 1 is back. At this time, calendar is no longer the value set by it, but on the road of thread 2 design. If multiple threads compete for the calendar object at the same time, various problems may occur, such as time mismatch and thread suspension.
After analyzing the implementation of the format, we can easily find that the only benefit of using the member variable calendar is that when subFormat is called, a parameter is missing, which brings about many problems. In fact, as long as a local variable is used here, all the problems will be solved.
There is a more important problem behind this problem-stateless: One of the advantages of stateless methods is that they can be called safely in various environments. To determine whether a method is stateful, it depends on whether it modifies other things, such as global variables, such as instance fields. The format method changes the calendar field of SimpleDateFormat during running, so it is stateful.

This also reminds us to pay attention to the following three points during system development and design:

1. When writing a public class on your own, you need to clearly describe the consequences of multi-threaded calls in the annotations.

2. Pay attention to thread security for every shared variable in the thread Environment

3. When designing our classes and methods, we should try our best to design them as stateless.

Iii. Solution

1. Create a new instance as needed:

    String formatDate(Date date)=  SimpleDateFormat("yyyy-MM-dd HH:mm:ss"  Date parse(String strDate) =  SimpleDateFormat("yyyy-MM-dd HH:mm:ss"

  Note:Creating an instance wherever necessary can avoid the problem of multi-threading no matter when the objects with thread security problems are changed from shared to local private, but it also increases the burden on Object creation. In general, this will not significantly affect the performance.

2. Use synchronization: Synchronize SimpleDateFormat objects

   SimpleDateFormat sdf =  SimpleDateFormat("yyyy-MM-dd HH:mm:ss"  String formatDate(Date date)  Date parse(String strDate) 

Note:When there are a large number of threads, when a thread calls this method, other threads that want to call this method need to block it. When the multi-thread concurrency is large, it will have a certain impact on the performance.

3. Use ThreadLocal:

   ThreadLocal<DateFormat> threadLocal =  ThreadLocal<DateFormat>  SimpleDateFormat("yyyy-MM-dd HH:mm:ss"  Date parse(String dateStr)  

Another method:

    String date_format = "yyyy-MM-dd HH:mm:ss"  ThreadLocal<DateFormat> threadLocal =  ThreadLocal<DateFormat>      =(df===   String formatDate(Date date)   Date parse(String strDate) 

  Note:The use of ThreadLocal also changes shared variables to exclusive. The exclusive thread can certainly reduce the overhead of creating objects in a concurrent environment than the exclusive method. If you have high performance requirements, this method is generally recommended.

4. Discard JDK and use the time format class in other class libraries:

  1. Use FastDateFormat in Apache commons to declare SimpleDateFormat, which is fast and thread-safe. Unfortunately, it can only format the date and cannot parse the date string.

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

To do a simple stress test, the method is the slowest and the method three is the fastest, but the performance of the Method One is not bad. Generally, the System Method One and method two can meet the requirements, so it is difficult to be the bottleneck of your system at this point. From a simple perspective, it is recommended to use method 1 or method 2. If you want to improve performance when necessary, you can use method 3 and ThreadLocal for caching.

The Joda-Time Class Library provides perfect Time processing methods. We recommend that you use it.

References:

1. http://dreamhead.blogbus.com/logs/215637834.html

2. http://www.blogjava.net/killme2008/archive/2011/07/10/354062.html

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.