Java ThreadLocal Thread Security solution _java

Source: Internet
Author: User
Tags dateformat

The reason why thread-safety problems arise

Thread safety problems are caused by global variables and static variables.

Ii. Thread-safety issues

Simpledateformate SDF = new SimpleDateFormat (); use Sdf.parse (DATESTR); Sdf.format (date); There is a reference to the Caleadar object within the SDF. In the source code sdf.parse (DATESTR); Calendar.clear (); and Calendar.gettime (); Time to get calendar

If thread A calls Sdf.parse () and Calendar.clear () has not executed calendar.gettime (), then thread B calls Sdf.parse (), and thread B executes the Sdf.clear () method , which causes the calendar data for thread A to be emptied;

Threadlocal is to use space to change time, synchronized is to use time to change space

Using threadlocal to resolve thread safety:

public class Threadlocaldateutil {
  private static final String Date_format = "Yyyy-mm-dd HH:mm:ss";
  private static threadlocal<dateformat> ThreadLocal = new threadlocal<dateformat> ();
 
  public static DateFormat GetDateFormat () 
  { 
    DateFormat df = Threadlocal.get (); 
    if (df==null) { 
      df = new SimpleDateFormat (date_format); 
      Threadlocal.set (DF); 
    } 
    return df; 
  } 
  public static String formatdate (date date) throws ParseException {return
    GetDateFormat (). Format (date);
  public static Date Parse (String strdate) throws ParseException {return
    GetDateFormat (). Parse (strdate);
  } 

Using the Synchronized solution:

public class Datesyncutil {
  private static SimpleDateFormat SDF = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");
    
  public static String formatdate (date date) throws parseexception{
    synchronized (SDF) {return
      Sdf.format (date);
    Public
   
  Static Date parse (String strdate) throws parseexception{
    synchronized (SDF) {
      return Sdf.parse (strdate);}}


Thank you for reading this article, I hope to help you, thank you for your support for this site!

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.