1. 程式人生 > >java.text.SimpleDateFormat多執行緒下的問題

java.text.SimpleDateFormat多執行緒下的問題

1. 今天在做效能壓測的時候發現java.text.SimpleDateFormat多執行緒下的錯誤

2. 先貼出兩段錯誤大家看一下:

Exception in thread "pool-1-thread-42" java.lang.NumberFormatException: multiple points  
    at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1084)  
    at java.lang.Double.parseDouble(Double.java:510)  
    at java.text.DigitList.getDouble(DigitList.java:151)  
    at java.text.DecimalFormat.parse(DecimalFormat.java:1303)  
    at java.text.SimpleDateFormat.subParse(SimpleDateFormat.java:1591)  
    at java.text.SimpleDateFormat.parse(SimpleDateFormat.java:1312)  
    at java.text.DateFormat.parse(DateFormat.java:335)  
    at infoair.obcs.utilities.DateTimeUtils.validateDateTime(DateTimeUtils.java:294)  
    at infoair.obcs.utilities.TestThread.run(DateTimeUtils.java:318)  
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)  
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)  
    at java.lang.Thread.run(Thread.java:619)  
Exception in thread "pool-1-thread-9" java.lang.NumberFormatException: For input string: ""  
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)  
    at java.lang.Long.parseLong(Long.java:431)  
    at java.lang.Long.parseLong(Long.java:468)  
    at java.text.DigitList.getLong(DigitList.java:177)  
    at java.text.DecimalFormat.parse(DecimalFormat.java:1298)  
    at java.text.SimpleDateFormat.subParse(SimpleDateFormat.java:1591)  
    at java.text.SimpleDateFormat.parse(SimpleDateFormat.java:1312)  
    at java.text.DateFormat.parse(DateFormat.java:335)  
    at infoair.obcs.utilities.DateTimeUtils.validateDateTime(DateTimeUtils.java:294)  
    at infoair.obcs.utilities.TestThread.run(DateTimeUtils.java:318)  
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)  
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)  
    at java.lang.Thread.run(Thread.java:619)  
分析:自己在本地debug的時候沒有任何問題,但是線上很奇怪。然後檢視jdk文件發現這個類不是執行緒安全的。
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.
解決方案:

在呼叫的程式碼中每次new一個就可以了。

參考:http://stackoverflow.com/questions/4021151/java-dateformat-is-not-threadsafe-what-does-this-leads-to