SimpleDateFormat安全的使用方法

来源:互联网 发布:mac互联网恢复功能 编辑:程序博客网 时间:2024/04/30 04:07

今天看到了一篇文章《深入理解Java:SimpleDateFormat安全的时间格式化》,引发了平时使用SimpleDataFormat的思考,特做此笔记.


因为平时开发中,使用到SimpleDateFormat的地方很多,所以会公用一个工具类

package com.example.mysim.mvpdemo.utilimport java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;public class DateUtils {        private static final  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");        public static  String formatDate(Date date)throws ParseException{        return sdf.format(date);    }        public static Date parse(String strDate) throws ParseException{        return sdf.parse(strDate);    }}


实际用起来听方便的,直到今天看到了开头的文章才发现自己还是太单纯咯. ps:此处应该来个大大的流汗表情

SimpleDateFormat这个类并不是线程安全的,并发的时候就会报错,但我们在使用的时候并未考虑到,而且JDK中并未说明这个类与线程安全有何关联,一下为JDK原文:
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.


下面我们通过看JDK源码来看看为什么SimpleDateFormat和DateFormat类不是线程安全的真正原因:
SimpleDateFormat继承了DateFormat,在DateFormat中定义了一个protected属性的 Calendar类的对象:calendar。只是因为Calendar累的概念复杂,牵扯到时区与本地化等等,Jdk的实现中使用了成员变量来传递参数,这就造成在多线程的时候会出现错误。


在format方法里,有这样一段代码:

private StringBuffer format(Date date, StringBuffer toAppendTo,                                FieldDelegate delegate) {        // Convert input date to time field list        calendar.setTime(date);    boolean useDateFormatSymbols = useDateFormatSymbols();        for (int i = 0; i < compiledPattern.length; ) {            int tag = compiledPattern[i] >>> 8;        int count = compiledPattern[i++] & 0xff;        if (count == 255) {        count = compiledPattern[i++] << 16;        count |= compiledPattern[i++];        }        switch (tag) {        case TAG_QUOTE_ASCII_CHAR:        toAppendTo.append((char)count);        break;        case TAG_QUOTE_CHARS:        toAppendTo.append(compiledPattern, i, count);        i += count;        break;        default:                subFormat(tag, count, delegate, toAppendTo, useDateFormatSymbols);        break;        }    }        return toAppendTo;    }

calendar.setTime(date)这条语句改变了calendar,稍后,calendar还会用到(在subFormat方法里),而这就是引发问题的根源。想象一下,在一个多线程环境下,有两个线程持有了同一个SimpleDateFormat的实例,分别调用format方法:
  线程1调用format方法,改变了calendar这个字段。
  中断来了。
  线程2开始执行,它也改变了calendar。
  又中断了。
  线程1回来了,此时,calendar已然不是它所设的值,而是走上了线程2设计的道路。如果多个线程同时争抢calendar对象,则会出现各种问题,时间不对,线程挂死等等。
  分析一下format的实现,我们不难发现,用到成员变量calendar,唯一的好处,就是在调用subFormat时,少了一个参数,却带来了这许多的问题。其实,只要在这里用一个局部变量,一路传递下去,所有问题都将迎刃而解。
  这个问题背后隐藏着一个更为重要的问题--无状态:无状态方法的好处之一,就是它在各种环境下,都可以安全的调用。衡量一个方法是否是有状态的,就看它是否改动了其它的东西,比如全局变量,比如实例的字段。format方法在运行过程中改动了SimpleDateFormat的calendar字段,所以,它是有状态的。

  这也同时提醒我们在开发和设计系统的时候注意下一下三点:

  1.自己写公用类的时候,要对多线程调用情况下的后果在注释里进行明确说明

  2.对线程环境下,对每一个共享的可变变量都要注意其线程安全性

  3.我们的类和方法在做设计的时候,要尽量设计成无状态的


三.解决办法

1.需要的时候创建新实例:

public class DateUtil {        public static  String formatDate(Date date)throws ParseException{         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");        return sdf.format(date);    }        public static Date parse(String strDate) throws ParseException{         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");        return sdf.parse(strDate);    }}

说明:在需要用到SimpleDateFormat 的地方新建一个实例,不管什么时候,将有线程安全问题的对象由共享变为局部私有都能避免多线程问题,不过也加重了创建对象的负担。在一般情况下,这样其实对性能影响比不是很明显的。

2.使用同步:同步SimpleDateFormat对象

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);        }    } }

说明:当线程较多时,当一个线程调用该方法时,其他想要调用此方法的线程就要block,多线程并发量大的时候会对性能有一定的影响。

3.使用ThreadLocal:

public class ConcurrentDateUtil {    private static ThreadLocal<DateFormat> threadLocal = new ThreadLocal<DateFormat>() {        @Override        protected DateFormat initialValue() {            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");        }    };    public static Date parse(String dateStr) throws ParseException {        return threadLocal.get().parse(dateStr);    }    public static String format(Date date) {        return threadLocal.get().format(date);    }}


另外一种写法:

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);    }   }

说明:使用ThreadLocal, 也是将共享变量变为独享,线程独享肯定能比方法独享在并发环境中能减少不少创建对象的开销。如果对性能要求比较高的情况下,一般推荐使用这种方法。


  4.抛弃JDK,使用其他类库中的时间格式化类:

  1.使用Apache commons 里的FastDateFormat,宣称是既快又线程安全的SimpleDateFormat, 可惜它只能对日期进行format, 不能对日期串进行解析。

  2.使用Joda-Time类库来处理时间相关问题

  

  做一个简单的压力测试,方法一最慢,方法三最快,但是就算是最慢的方法一性能也不差,一般系统方法一和方法二就可以满足,所以说在这个点很难成为你系统的瓶颈所在。从简单的角度来说,建议使用方法一或者方法二,如果在必要的时候,追求那么一点性能提升的话,可以考虑用方法三,用ThreadLocal做缓存。

  Joda-Time类库对时间处理方式比较完美,建议使用。


根据业务使用场景,目前使用方法2.

转载博客:http://www.cnblogs.com/peida/archive/2013/05/31/3070790.html


原创粉丝点击