• 案例(2)-- 线程不安全对象(SimpleDateFormat)


    问题描述:

      1、系统偶发性抛出异常:java.lang.NumberFormatException: multiple points ,追溯源头抛出的类为:SimpleDateFormat

    问题的定位:

      1、总所周知,SimpleDateFormat是非线程安全的类。由此可以推断:在多线程环境下,需要同步使用。

      2、模拟异常的发生: 

    重现错误代码示例:

    public class ThreadSafe {
    
      public static void main(String[] args) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        new Thread(new MyThread1(sdf,"1991-06-10 10:21:10"),"a").start();
        new Thread(new MyThread1(sdf,"1991-07-10 17:21:19"),"b").start();
        new Thread(new MyThread1(sdf,"1989-11-19 15:31:40"),"b").start();
        new Thread(new MyThread1(sdf,"1999-08-12 13:41:40"),"b").start();
        new Thread(new MyThread1(sdf,"2019-06-10 10:23:10"),"b").start();
        new Thread(new MyThread1(sdf,"1990-06-10 55:55:55"),"b").start();
        new Thread(new MyThread1(sdf,sdf.format(new Date())),"b").start();
      }
    }
    class MyThread1 implements Runnable{
      SimpleDateFormat sdf;
      String dateStr;
    
      public MyThread1(SimpleDateFormat sdf,String dateStr) {
        this.sdf = sdf;
        this.dateStr = dateStr;
      }
    
      @Override
      public void run() {
        while (true){
          try {
            String format = sdf.format(new Date());
            Date parse = sdf.parse(format);
            System.out.println(format+","+parse+","+Thread.currentThread().getName());
          }catch (Exception error){
            error.printStackTrace();
            System.exit(-1); //为了方便查看日志,停掉整个进程
          }
        }
      }
    }
    

    完整的异常堆栈信息如下:

    java.lang.NumberFormatException: multiple points
    	at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1890)
    	at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
    	at java.lang.Double.parseDouble(Double.java:538)
    	at java.text.DigitList.getDouble(DigitList.java:169)
    	at java.text.DecimalFormat.parse(DecimalFormat.java:2056)
    	at java.text.SimpleDateFormat.subParse(SimpleDateFormat.java:1869)
    

    问题的解决:  

       1、将 SimpleDateFormat 结合 ThreadLocal 构建工具类,使得一个线程,专属一个 SimpleDateFormat 。

       2、工具类示例代码如下:

        (暂缺)    

       

  • 相关阅读:
    存储过程sql拼接
    收集 一个数字转大写金额的方法
    判断打印机是否可用
    TortoiseSVN解决冲突
    特殊符号
    [转]Winform用匿名方法新建线程的方法
    [转]利用SqlBulkCopy快速大批量导入数据(SqlBulkCopy强大)
    DevExpress GridControl使用
    GridView自动调整列宽
    'display','position'和'float'相互关系
  • 原文地址:https://www.cnblogs.com/chen--biao/p/11351093.html
Copyright © 2020-2023  润新知