Using DateFormat classes in Java multithreaded programming _java

Source: Internet
Author: User
Tags dateformat datetime

The DateFormat class is a non thread-safe class. The Javadocs document mentions that "Date formats is not synchronized." We recommend that you create separate date formats for each thread. If multiple threads simultaneously access a date format, this requires the addition of a synchronized code block externally. "

The following code shows us how to use DateFormat to convert a string date to a Date object in a thread environment. Creating an instance to get the date format is more efficient because the system does not need to acquire the local language and the country multiple times.

public class Dateformattest {
 
 private final DateFormat format =
      new SimpleDateFormat ("YyyyMMdd");
 
 Public date convert (String source)
           throws parseexception{
  Date d = format.parse (source);
  return D;
 }
}

This piece of code is not thread safe. We can call it in multiple threads. In the code that is called, I created a thread pool with two threads, submitted 5 date conversion tasks, and then looked at the results of the run:

Final Dateformattest T =new dateformattest ();
Callable<date> task =new callable<date> () {public
  Date called () throws Exception {return
    T.convert (" 20100811 ");
  }
;
 
Let's try the case of 2 threads
Executorservice exec = Executors.newfixedthreadpool (2);
list<future<date>> results =
       new arraylist<future<date>> ();
 
Implement 5-time date conversion for
(int i =0 i <5; i++) {
  Results.add (Exec.submit (Task));
}
Exec.shutdown ();
 
View results for
(future<date> result:results) {
  System.out.println (Result.get ());
}

The code doesn't run as we'd like-sometimes it prints out the right date and sometimes it prints the wrong (for example,. Sat 00:00:00 BST 2012), sometimes even throws numberformatexception!


How to use the DateFormat class concurrently

We can use the DateFormat class in a variety of ways with thread safety.

1. Sync

The easiest way to do this is to lock the DateFormat object before making a date conversion. This method allows only one thread to access the DateFormat object at a time, while other threads can only wait.

Public Date convert (String source)
          throws parseexception{
 synchronized (format) {
  Date d = format.parse ( source);
  return D;
 }
}


2. Use of threadlocal

Another approach is to use the threadlocal variable to hold the DateFormat object, which means that each thread has a copy of its own and does not have to wait for other threads to release it. This approach can be more efficient than using synchronized blocks.

public class Dateformattest {
 
 private static final threadlocal<dateformat> df
         = new threadlocal< Dateformat> () {
  @Override
  protected DateFormat initialvalue () {return
    new SimpleDateFormat (" YyyyMMdd ");
  }
 ;
 
 Public date convert (String source)
           throws parseexception{
  Date d = Df.get (). Parse (source);
  return D;
 }
}

3. Joda-time

Joda-time is a great alternative to the open source JDK's date and calendar APIs, and its datetimeformat is thread safe and unchanging.


Import Org.joda.time.DateTime;
Import Org.joda.time.format.DateTimeFormat;
Import Org.joda.time.format.DateTimeFormatter;
Import java.util.Date;
 
public class Dateformattest {
 
 private final datetimeformatter FMT =
    Datetimeformat.forpattern ("YyyyMMdd");
 
 Public Date convert (String source) {
  DateTime d = fmt.parsedatetime (source);
  Returnd.todate ();
 }


Related Article

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.