java中使用代码证明SimpleDateFormat非线程安全,如何解决类似问题

异常重现

实现代码如下:

public static final SimpleDateFormat dataFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    
public static void main(String[] args) {
    ExecutorService executorService = Executors.newCachedThreadPool();
    List<String> dateStrList =
            Arrays.asList(new String[] {"2019-05-28 10:21:04", "2019-04-28 10:11:01",
                    "2019-05-25 09:11:01", "2019-05-18 10:16:01", "2018-05-28 10:11:01"});
    
    for (String s : dateStrList) {
        executorService.execute(() -> {
            try {
                Date date = dataFormat.parse(s);
                System.out.println(date);
                
                TimeUnit.SECONDS.sleep(1);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }
}

使用ExecutorService 创建线程池,然后使用线程池执行parse代码,结果抛出异常

java.lang.NumberFormatException: For input string: ""
	at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
	at java.lang.Long.parseLong(Long.java:601)
	at java.lang.Long.parseLong(Long.java:631)
	at java.text.DigitList.getLong(DigitList.java:195)
	at java.text.DecimalFormat.parse(DecimalFormat.java:2051)
	at java.text.SimpleDateFormat.subParse(SimpleDateFormat.java:2162)
	at java.text.SimpleDateFormat.parse(SimpleDateFormat.java:1514)
	at java.text.DateFormat.parse(DateFormat.java:364)
	at com.dxz.property.statics.TestTiger.lambda$0(TestTiger.java:23)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
	at java.lang.Thread.run(Thread.java:745)
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)
	at java.text.SimpleDateFormat.parse(SimpleDateFormat.java:1514)
	at java.text.DateFormat.parse(DateFormat.java:364)
	at com.dxz.property.statics.TestTiger.lambda$0(TestTiger.java:23)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
	at java.lang.Thread.run(Thread.java:745)
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)
	at java.text.SimpleDateFormat.parse(SimpleDateFormat.java:1514)
	at java.text.DateFormat.parse(DateFormat.java:364)
	at com.dxz.property.statics.TestTiger.lambda$0(TestTiger.java:23)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
	at java.lang.Thread.run(Thread.java:745)
Thu May 25 09:11:01 CST 2220
Thu Nov 07 10:16:01 CST 2024

怎么解决该问题

SimpleDateFormat在对时间进行格式化的方法format中,会先对calendar对象进行setTime的赋值,若是有多个线程同时操作一个SimpleDateFormat实例的话,就会对calendar的赋值进行覆盖,进而产生问题。

有三种方法可以解决这个问题:

1.在每次需要使用的时候,进行SimpleDateFormat实例的创建,这种方式会导致创建一些对象实例,占用一些内存,不建议这样使用。

实现代码如下:

 public static void main(String[] args) {
    ExecutorService executorService = Executors.newCachedThreadPool();
    List<String> dateStrList =
            Arrays.asList(new String[] {"2019-05-28 10:21:04", "2019-04-28 10:11:01",
                    "2019-05-25 09:11:01", "2019-05-18 10:16:01", "2018-05-28 10:11:01"});
    
    for (String s : dateStrList) {
        executorService.execute(() -> {
            try {
                SimpleDateFormat dataFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                Date date = dataFormat.parse(s);
                System.out.println(date);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }
}

输出结果如下:

Mon May 28 10:11:01 CST 2018
Sat May 18 10:16:01 CST 2019
Tue May 28 10:21:04 CST 2019
Sat May 25 09:11:01 CST 2019
Sun Apr 28 10:11:01 CST 2019

2.使用同步的方式,在调用方法的时候加上synchronized,这样可以让线程调用方法时,进行加锁,也就是会造成线程间的互斥,对性能影响比较大。

实现代码如下:

public static void main(String[] args) {
    ExecutorService executorService = Executors.newCachedThreadPool();
    List<String> dateStrList =
            Arrays.asList(new String[] {"2019-05-28 10:21:04", "2019-04-28 10:11:01",
                    "2019-05-25 09:11:01", "2019-05-18 10:16:01", "2018-05-28 10:11:01"});
                    
    SimpleDateFormat dataFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    
    for (String s : dateStrList) {
        executorService.execute(() -> {
        
            try {
                synchronized(dataFormat){
                    Date date = dataFormat.parse(s);
                    System.out.println(date);
                }
                TimeUnit.SECONDS.sleep(1);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        
    }
}

输出结果如下:

Sun Apr 28 10:11:01 CST 2019
Sat May 18 10:16:01 CST 2019
Mon May 28 10:11:01 CST 2018
Sat May 25 09:11:01 CST 2019
Tue May 28 10:21:04 CST 2019

3.使用ThreadLocal进行保存,相当于一个线程只会有一个实例,进而减少了实例数量,也防止了线程间的互斥,推荐使用这种方式。

实现代码如下:

public static void main(String[] args) {
    ExecutorService executorService = Executors.newCachedThreadPool();
    List<String> dateStrList =
            Arrays.asList(new String[] {"2019-05-28 10:21:04", "2019-04-28 10:11:01",
                    "2019-05-25 09:11:01", "2019-05-18 10:16:01", "2018-05-28 10:11:01"});
    
    ThreadLocal<SimpleDateFormat> threadLocal = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        }
    };

    for (String s : dateStrList) {
        executorService.execute(() -> {
            try {
                Date date = threadLocal.get().parse(s);
                System.out.println(date);
                
                TimeUnit.SECONDS.sleep(1);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }
}

输出结果如下:

Sat May 18 10:16:01 CST 2019
Tue May 28 10:21:04 CST 2019
Sun Apr 28 10:11:01 CST 2019
Mon May 28 10:11:01 CST 2018
Sat May 25 09:11:01 CST 2019
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值