案例-- 线程不安全对象(SimpleDateFormat)
Posted chen--biao
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了案例-- 线程不安全对象(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、工具类示例代码如下:
(暂缺)
以上是关于案例-- 线程不安全对象(SimpleDateFormat)的主要内容,如果未能解决你的问题,请参考以下文章