zoukankan      html  css  js  c++  java
  • 案例(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、工具类示例代码如下:

        (暂缺)    

       

  • 相关阅读:
    RTP时间戳
    FAT,FAT32,NTFS单目录文件数量限制
    SWT将系统图标保存为本地文件
    HttpClient+jsoup登录+解析 163邮箱
    RTP协议分析
    Java and unsigned int, unsigned short, unsigned byte, unsigned long, etc. (Or rather, the lack thereof)
    YUV转为RGB24及IplImage格式(I420和YV12)及Java版实现
    Using a long as ArrayList index in java
    详解 SWT 中的 Browser.setUrl(String url, String postData, String[] headers) 的用法
    swt生成、jar可执行包生成.exe可执行文件(giter)
  • 原文地址:https://www.cnblogs.com/chen--biao/p/11351093.html
Copyright © 2011-2022 走看看