zoukankan      html  css  js  c++  java
  • 【JAVA】JDK-SimpleDataFormat 线程不安全!

    【问题】

    publicclassProveNotSafe {
        staticSimpleDateFormat df = newSimpleDateFormat("dd-MMM-yyyy", Locale.US);
        staticString testdata[] = { "01-Jan-1999", "14-Feb-2001", "31-Dec-2007"};
     
        publicstaticvoidmain(String[] args) {
            Runnable r[] = newRunnable[testdata.length];
            for(inti = 0; i < r.length; i++) {
                finalinti2 = i;
                r[i] = newRunnable() {
                    publicvoidrun() {
                        try{
                            for(intj = 0; j < 1000; j++) {
                                String str = testdata[i2];
                                String str2 = null;
                                /* synchronized(df) */{
                                    Date d = df.parse(str);
                                    str2 = df.format(d);
                                    System.out.println("i: "+ i2 + "	j: "+ j + "	ThreadID: "
                                            + Thread.currentThread().getId() + "	ThreadName: "
                                            + Thread.currentThread().getName() + "	"+ str + "	"+ str2);
                                }
                                if(!str.equals(str2)) {
                                    thrownewRuntimeException("date conversion failed after "+ j
                                            + " iterations. Expected "+ str + " but got "+ str2);
                                }
                            }
                        } catch(ParseException e) {
                            thrownewRuntimeException("parse failed");
                        }
                    }
                };
                newThread(r[i]).start();
            }
        }
    }
    

      

    测试结果
    i: 2    j: 0    ThreadID: 10    ThreadName: Thread-2    31-Dec-200731-Dec-2007
    i: 2    j: 1    ThreadID: 10    ThreadName: Thread-2    31-Dec-200731-Dec-2007
    i: 2    j: 2    ThreadID: 10    ThreadName: Thread-2    31-Dec-200731-Dec-2007
    i: 2    j: 3    ThreadID: 10    ThreadName: Thread-2    31-Dec-200731-Dec-2007
    i: 2    j: 4    ThreadID: 10    ThreadName: Thread-2    31-Dec-200731-Dec-2007
    i: 2    j: 5    ThreadID: 10    ThreadName: Thread-2    31-Dec-200731-Dec-2007
    i: 2    j: 6    ThreadID: 10    ThreadName: Thread-2    31-Dec-200731-Dec-2007
    i: 2    j: 7    ThreadID: 10    ThreadName: Thread-2    31-Dec-200731-Dec-2007
    i: 2    j: 8    ThreadID: 10    ThreadName: Thread-2    31-Dec-200731-Dec-2007
    i: 2    j: 9    ThreadID: 10    ThreadName: Thread-2    31-Dec-200731-Dec-2007
    i: 2    j: 10   ThreadID: 10    ThreadName: Thread-2    31-Dec-200731-Dec-2007
    i: 2    j: 11   ThreadID: 10    ThreadName: Thread-2    31-Dec-200731-Dec-2007
    i: 2    j: 12   ThreadID: 10    ThreadName: Thread-2    31-Dec-200731-Dec-2007
    i: 2    j: 13   ThreadID: 10    ThreadName: Thread-2    31-Dec-200731-Dec-2007
    i: 2    j: 14   ThreadID: 10    ThreadName: Thread-2    31-Dec-200731-Dec-2007
    i: 2    j: 15   ThreadID: 10    ThreadName: Thread-2    31-Dec-200731-Dec-2007
    i: 2    j: 16   ThreadID: 10    ThreadName: Thread-2    31-Dec-200731-Dec-2007
    i: 2    j: 17   ThreadID: 10    ThreadName: Thread-2    31-Dec-200711-Jan-1999
    i: 0    j: 0    ThreadID: 8ThreadName: Thread-0    01-Jan-199911-Jan-1999
    Exception in thread "Thread-2"i: 1j: 0    ThreadID: 9ThreadName: Thread-1    14-Feb-200111-Jan-2001
    Exception in thread "Thread-0"java.lang.RuntimeException: date conversion failed after 0iterations. Expected 01-Jan-1999but got 11-Jan-1999
        at test.date.ProveNotSafe$1.run(ProveNotSafe.java:30)
        at java.lang.Thread.run(Thread.java:619)
    Exception in thread "Thread-1"java.lang.RuntimeException: date conversion failed after 0iterations. Expected 14-Feb-2001but got 11-Jan-2001
        at test.date.ProveNotSafe$1.run(ProveNotSafe.java:30)
        at java.lang.Thread.run(Thread.java:619)
    java.lang.RuntimeException: date conversion failed after 17iterations. Expected 31-Dec-2007but got 11-Jan-1999
        at test.date.ProveNotSafe$1.run(ProveNotSafe.java:30)
        at java.lang.Thread.run(Thread.java:619)

     

    [问题原因]

          SimpleDateFormat和DateFormat类不是线程安全的。我们之所以忽视线程安全的问题,是因为从SimpleDateFormat和DateFormat类提供给我们的接口上来看,实在让人看不出它与线程安全有何相干。只是在JDK文档的最下面有如下说明:

    SimpleDateFormat中的日期格式不是同步的。推荐(建议)为每个线程创建独立的格式实例。如果多个线程同时访问一个格式,则它必须保持外部同步。

      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的实现中使用了成员变量来传递参数,这就造成在多线程的时候会出现错误。

     
    有这样一段代码:
    父类: DateFormat
    protected Calendar calendar;
     
    子类 :   SimpleDateFormat
       // Called from Format after creating a FieldDelegate
        private StringBuffer format(Date date, StringBuffer toAppendTo,
                                    FieldDelegate delegate) {
            // Convert input date to time field list
            calendar.setTime(date);
    
            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);
      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.需要的时候创建新实例:
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      2.同步代码块 synchronized(code)
    privatestatic SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
          
        publicstatic String formatDate(Date date)throws ParseException{
            synchronized(sdf){
                return sdf.format(date);
            }  
        }
        
        publicstatic Date parse(String strDate) throws ParseException{
            synchronized(sdf){
                return sdf.parse(strDate);
            }
        } 
      3.使用ThreadLocal:
    也是将共享变量变为独享,线程独享肯定能比方法独享在并发环境中能减少不少创建对象的开销。如果对性能要求比较高的情况下,一般推荐使用这种方法。
    privatestatic ThreadLocal<SimpleDateFormate> threadLocal = new ThreadLocal<SimpleDateFormate>(); 
     
  • 相关阅读:
    剑指Offer-46.孩子们的游戏(圆圈中最后剩下的数)(C++/Java)
    剑指Offer-45.扑克牌顺子(C++/Java)
    剑指Offer-44.翻转单词顺序列(C++/Java)
    剑指Offer-43.左旋转字符串(C++/Java)
    剑指Offer-42.和为S的两个数字(C++/Java)
    剑指Offer-41.和为S的连续正数序列(C++/Java)
    剑指Offer-40.数组中只出现一次的数字(C++/Java)
    剑指Offer-39.把数组排成最小的数(C++/Java)
    Codeforces Round #316 (Div. 2) D Tree Requests
    URAL 1774 Barber of the Army of Mages (最大流)
  • 原文地址:https://www.cnblogs.com/liuyongcn/p/5338870.html
Copyright © 2011-2022 走看看