在日常开发中,我们经常会用到时间相关类,我们有很多办法在Java代码中获取时间。但是不同的方法获取到的时间的格式都不尽相同,这时候就需要一种格式化工具,把时间显示成我们需要的格式。
最常用的方法就是使用SimpleDateFormat类。这是一个看上去功能比较简单的类,但是,一旦使用不当也有可能导致很大的问题。
在阿里巴巴Java开发手册中,有如下明确规定:
SimpleDateFormat 不允许定义为satic 若定义为static 必须枷锁或者用dateUtils类
那么,本文就围绕SimpleDateFormat的用法、原理等来深入分析下如何以正确的姿势使用它。
重现SimpleDateFormat类的线程安全问题
package com.liu.news.common.utils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
/**
* @author lx
* @version 1.0
* @description: 测试SimpleDateFormat的线程不安全问题
* @date 2021/8/11 8:06
*/
public class SimpleDateFormatTest01 {
//执行总次数
private static final int EXECUTE_COUNT = 1000;
//同时运行的线程数量
private static final int THREAD_COUNT = 20;
//SimpleDateFormat对象
private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
public static void main(String[] args) throws InterruptedException {
final Semaphore semaphore = new Semaphore(THREAD_COUNT);
final CountDownLatch countDownLatch = new CountDownLatch(EXECUTE_COUNT);
ExecutorService executorService = Executors.newCachedThreadPool();
for (int i = 0; i < EXECUTE_COUNT; i++){
executorService.execute(() -> {
try {
semaphore.acquire();
try {
Date date = simpleDateFormat.parse("2021-08-01");
System.out.println(date);
} catch (ParseException e) {
System.out.println("线程:" + Thread.currentThread().getName() + " 格式化日期失败");
e.printStackTrace();
System.exit(1);
}catch (NumberFormatException e){
System.out.println("线程:" + Thread.currentThread().getName() + " 格式化日期失败");
e.printStackTrace();
System.exit(1);
}
semaphore.release();
} catch (InterruptedException e) {
System.out.println("信号量发生错误");
e.printStackTrace();
System.exit(1);
}
countDownLatch.countDown();
});
}
countDownLatch.await();
executorService.shutdown();
System.out.println("所有线程格式化日期成功");
}
}
运行程序,结果如下
D:\soft\jdk\jdk1.8.0_45\bin\java.exe -javaagent:C:\Users\lx\.IntelliJIdea2018.3\system\testAgent\intellij-coverage-agent-1.0.495.jar=C:\Users\lx\AppData\Local\Temp\coverage1args "-javaagent:D:\soft\idea\IntelliJ IDEA 2018.3.2\lib\idea_rt.jar=13822:D:\soft\idea\IntelliJ IDEA 2018.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\soft\jdk\jdk1.8.0_45\jre\lib\charsets.jar;D:\soft\jdk\jdk1.8.0_45\jre\lib\deploy.jar;D:\soft\jdk\jdk1.8.0_45\jre\lib\ext\access-bridge-64.jar;D:\soft\jdk\jdk1.8.0_45\jre\lib\ext\cldrdata.jar;D:\soft\jdk\jdk1.8.0_45\jre\lib\ext\dnsns.jar;D:\soft\jdk\jdk1.8.0_45\jre\lib\ext\jaccess.jar;D:\soft\jdk\jdk1.8.0_45\jre\lib\ext\jfxrt.jar;D:\soft\jdk\jdk1.8.0_45\jre\lib\ext\localedata.jar;D:\soft\jdk\jdk1.8.0_45\jre\lib\ext\nashorn.jar;D:\soft\jdk\jdk1.8.0_45\jre\lib\ext\sunec.jar;D:\soft\jdk\jdk1.8.0_45\jre\lib\ext\sunjce_provider.jar;D:\soft\jdk\jdk1.8.0_45\jre\lib\ext\sunmscapi.jar;D:\soft\jdk\jdk1.8.0_45\jre\lib\ext\sunpkcs11.jar;D:\soft\jdk\jdk1.8.0_45\jre\lib\ext\zipfs.jar;D:\soft\jdk\jdk1.8.0_45\jre\lib\javaws.jar;D:\soft\jdk\jdk1.8.0_45\jre\lib\jce.jar;D:\soft\jdk\jdk1.8.0_45\jre\lib\jfr.jar;D:\soft\jdk\jdk1.8.0_45\jre\lib\jfxswt.jar;D:\soft\jdk\jdk1.8.0_45\jre\lib\jsse.jar;D:\soft\jdk\jdk1.8.0_45\jre\lib\management-agent.jar;D:\soft\jdk\jdk1.8.0_45\jre\lib\plugin.jar;D:\soft\jdk\jdk1.8.0_45\jre\lib\resources.jar;D:\soft\jdk\jdk1.8.0_45\jre\lib\rt.jar;E:\daima\nacosYM\newsartical\artical-common\artical-common-utils\target\classes;D:\env\repo\cn\hutool\hutool-all\5.7.4\hutool-all-5.7.4.jar;D:\env\repo\org\projectlombok\lombok\1.18.20\lombok-1.18.20.jar;D:\env\repo\org\apache\commons\commons-lang3\3.11\commons-lang3-3.11.jar;D:\env\repo\org\apache\commons\commons-collections4\4.4\commons-collections4-4.4.jar;D:\env\repo\commons-configuration\commons-configuration\1.10\commons-configuration-1.10.jar;D:\env\repo\commons-lang\commons-lang\2.6\commons-lang-2.6.jar;D:\env\repo\commons-logging\commons-logging\1.1.1\commons-logging-1.1.1.jar;D:\env\repo\com\alibaba\fastjson\1.2.76\fastjson-1.2.76.jar com.liu.news.common.utils.SimpleDateFormatTest01
---- IntelliJ IDEA coverage runner ----
sampling ...
include patterns:
com\.liu\.news\.common\.utils\..*
exclude patterns:
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sat Jan 01 00:00:00 CST 1686856
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Mon Aug 01 00:00:00 CST 1
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
线程:pool-1-thread-3 格式化日期失败
线程:pool-1-thread-4 格式化日期失败
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.liu.news.common.utils.SimpleDateFormatTest01.lambda$main$0(SimpleDateFormatTest01.java:37)
at com.liu.news.common.utils.SimpleDateFormatTest01$$Lambda$1/500977346.run(Unknown Source)
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)
Sun Aug 01 00:00:00 CST 2021
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.liu.news.common.utils.SimpleDateFormatTest01.lambda$main$0(SimpleDateFormatTest01.java:37)
at com.liu.news.common.utils.SimpleDateFormatTest01$$Lambda$1/500977346.run(Unknown Source)
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)
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
线程:pool-1-thread-8 格式化日期失败
java.lang.NumberFormatException: multiple points
线程:pool-1-thread-7 格式化日期失败
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.liu.news.common.utils.SimpleDateFormatTest01.lambda$main$0(SimpleDateFormatTest01.java:37)
at com.liu.news.common.utils.SimpleDateFormatTest01$$Lambda$1/500977346.run(Unknown Source)
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.liu.news.common.utils.SimpleDateFormatTest01.lambda$main$0(SimpleDateFormatTest01.java:37)
at com.liu.news.common.utils.SimpleDateFormatTest01$$Lambda$1/500977346.run(Unknown Source)
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)
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Wed Aug 11 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sat Aug 01 00:00:00 CST 11
线程:pool-1-thread-15 格式化日期失败
java.lang.NumberFormatException: multiple points
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1890)
at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)Sun Aug 01 00:00:00 CST 2021
at java.lang.Double.parseDouble(Double.java:538)
线程:pool-1-thread-12 格式化日期失败 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.liu.news.common.utils.SimpleDateFormatTest01.lambda$main$0(SimpleDateFormatTest01.java:37)
at com.liu.news.common.utils.SimpleDateFormatTest01$$Lambda$1/500977346.run(Unknown Source)
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)
Sun Aug 01 00:00:00 CST 2021
java.lang.NumberFormatException: multiple points
Sun Aug 01 00:00:00 CST 2021
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1890)
Sun Aug 01 00:00:00 CST 2021
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.liu.news.common.utils.SimpleDateFormatTest01.lambda$main$0(SimpleDateFormatTest01.java:37)
at com.liu.news.common.utils.SimpleDateFormatTest01$$Lambda$1/500977346.run(Unknown Source)
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)
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
线程:pool-1-thread-20 格式化日期失败
java.lang.NumberFormatException: multiple points
线程:pool-1-thread-19 格式化日期失败
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.liu.news.common.utils.SimpleDateFormatTest01.lambda$main$0(SimpleDateFormatTest01.java:37)
at com.liu.news.common.utils.SimpleDateFormatTest01$$Lambda$1/500977346.run(Unknown Source)
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
Sun Aug 01 00:00:00 CST 2021 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.liu.news.common.utils.SimpleDateFormatTest01.lambda$main$0(SimpleDateFormatTest01.java:37)
at com.liu.news.common.utils.SimpleDateFormatTest01$$Lambda$1/500977346.run(Unknown Source)
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)
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
线程:pool-1-thread-44 格式化日期失败
Fri May 01 00:00:00 CST 2189
Fri May 01 00:00:00 CST 2189
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:1869)
at java.text.SimpleDateFormat.parse(SimpleDateFormat.java:1514)
Sun Aug 01 00:00:00 CST 2021
at java.text.DateFormat.parse(DateFormat.java:364)
at com.liu.news.common.utils.SimpleDateFormatTest01.lambda$main$0(SimpleDateFormatTest01.java:37)
at com.liu.news.common.utils.SimpleDateFormatTest01$$Lambda$1/500977346.run(Unknown Source)
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)
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
线程:pool-1-thread-43 格式化日期失败
java.lang.NumberFormatException: For input string: ""
Sun Aug 01 00:00:00 CST 1
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Long.parseLong(Long.java:601)
at java.lang.Long.parseLong(Long.java:631)
Sun Aug 01 00:00:00 CST 2021 at java.text.DigitList.getLong(DigitList.java:195)
at java.text.DecimalFormat.parse(DecimalFormat.java:2051)
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.liu.news.common.utils.SimpleDateFormatTest01.lambda$main$0(SimpleDateFormatTest01.java:37)
at com.liu.news.common.utils.SimpleDateFormatTest01$$Lambda$1/500977346.run(Unknown Source)
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)
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Mon Aug 01 00:00:00 CST 2022
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Mon Aug 01 00:00:00 CST 2022
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
线程:pool-1-thread-60 格式化日期失败
java.lang.NumberFormatException: multiple points
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1890)
线程:pool-1-thread-51 格式化日期失败
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)
Sun Aug 01 00:00:00 CST 2021
at com.liu.news.common.utils.SimpleDateFormatTest01.lambda$main$0(SimpleDateFormatTest01.java:37)
at com.liu.news.common.utils.SimpleDateFormatTest01$$Lambda$1/500977346.run(Unknown Source)
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)
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
java.lang.NumberFormatException: multiple points
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1890)
Sun Aug 01 00:00:00 CST 2021
at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 1
Sun Aug 01 00:00:00 CST 1
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
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.liu.news.common.utils.SimpleDateFormatTest01.lambda$main$0(SimpleDateFormatTest01.java:37)
at com.liu.news.common.utils.SimpleDateFormatTest01$$Lambda$1/500977346.run(Unknown Source)
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)
Sun Aug 01 00:00:00 CST 2021
Class transformation time: 0.1343094s for 306 classes or 4.389196078431372E-4s per class
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sat Jul 31 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
线程:pool-1-thread-637 格式化日期失败
Sun Aug 01 00:00:00 CST 2021java.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:1869)
Wed Dec 01 00:00:00 CST 2021
at java.text.SimpleDateFormat.parse(SimpleDateFormat.java:1514)
at java.text.DateFormat.parse(DateFormat.java:364)
at com.liu.news.common.utils.SimpleDateFormatTest01.lambda$main$0(SimpleDateFormatTest01.java:37)
at com.liu.news.common.utils.SimpleDateFormatTest01$$Lambda$1/500977346.run(Unknown Source)
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)
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Mon Oct 01 00:00:00 CST 2187
Mon Dec 01 00:00:00 CST 1969
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Tue Dec 01 00:00:00 CST 2020
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Mon Aug 01 00:00:00 CST 1
Sun Aug 01 00:00:00 CST 2021
Mon Oct 01 00:00:00 CST 2187
Sun Aug 01 00:00:00 CST 2021
Sun Aug 01 00:00:00 CST 2021
Process finished with exit code 1
解决SimpleDateFormat类的线程安全问题
1.局部变量法
最简单的一种方式就是将SimpleDateFormat类对象定义成局部变量,如下所示的代码,将SimpleDateFormat类对象定义在parse(String)方法的上面,即可解决问题。
package com.liu.news.common.utils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
/**
* @author lx
* @version 1.0
* @description: 测试SimpleDateFormat的线程不安全问题
* @date 2021/8/11 8:06
*/
public class SimpleDateFormatTest01 {
//执行总次数
private static final int EXECUTE_COUNT = 1000;
//同时运行的线程数量
private static final int THREAD_COUNT = 20;
//SimpleDateFormat对象
// private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
public static void main(String[] args) throws InterruptedException {
final Semaphore semaphore = new Semaphore(THREAD_COUNT);
final CountDownLatch countDownLatch = new CountDownLatch(EXECUTE_COUNT);
ExecutorService executorService = Executors.newCachedThreadPool();
for (int i = 0; i < EXECUTE_COUNT; i++){
executorService.execute(() -> {
try {
semaphore.acquire();
try {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = simpleDateFormat.parse("2021-08-01");
System.out.println(date);
} catch (ParseException e) {
System.out.println("线程:" + Thread.currentThread().getName() + " 格式化日期失败");
e.printStackTrace();
System.exit(1);
}catch (NumberFormatException e){
System.out.println("线程:" + Thread.currentThread().getName() + " 格式化日期失败");
e.printStackTrace();
System.exit(1);
}
semaphore.release();
} catch (InterruptedException e) {
System.out.println("信号量发生错误");
e.printStackTrace();
System.exit(1);
}
countDownLatch.countDown();
});
}
countDownLatch.await();
executorService.shutdown();
System.out.println("所有线程格式化日期成功");
}
}
所有线程格式化日期成功
Class transformation time: 0.1085764s for 293 classes or 3.7056791808873723E-4s per class
不足之处
这种方式在高并发下会创建大量的SimpleDateFormat类对象,影响程序的性能,所以,这种方式在实际生产环境不太被推荐。
synchronized锁方式
将SimpleDateFormat类对象定义成全局静态变量,此时所有线程共享SimpleDateFormat类对象,此时在调用格式化时间的方法时,对SimpleDateFormat对象进行同步即可,代码如下所示。
package com.liu.news.common.utils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
/**
* @author lx
* @version 1.0
* @description: 测试SimpleDateFormat的线程不安全问题
* @date 2021/8/11 8:06
*/
public class SimpleDateFormatTest01 {
//执行总次数
private static final int EXECUTE_COUNT = 1000;
//同时运行的线程数量
private static final int THREAD_COUNT = 20;
//SimpleDateFormat对象
private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
public static void main(String[] args) throws InterruptedException {
final Semaphore semaphore = new Semaphore(THREAD_COUNT);
final CountDownLatch countDownLatch = new CountDownLatch(EXECUTE_COUNT);
ExecutorService executorService = Executors.newCachedThreadPool();
for (int i = 0; i < EXECUTE_COUNT; i++){
executorService.execute(() -> {
try {
semaphore.acquire();
try {
// SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
synchronized (simpleDateFormat) {
Date date = simpleDateFormat.parse("2021-08-01");
System.out.println(date);
}
} catch (ParseException e) {
System.out.println("线程:" + Thread.currentThread().getName() + " 格式化日期失败");
e.printStackTrace();
System.exit(1);
}catch (NumberFormatException e){
System.out.println("线程:" + Thread.currentThread().getName() + " 格式化日期失败");
e.printStackTrace();
System.exit(1);
}
semaphore.release();
} catch (InterruptedException e) {
System.out.println("信号量发生错误");
e.printStackTrace();
System.exit(1);
}
countDownLatch.countDown();
});
}
countDownLatch.await();
executorService.shutdown();
System.out.println("所有线程格式化日期成功");
}
}
不足
虽然这种方式能够解决SimpleDateFormat类的线程安全问题,但是由于在程序的执行过程中,为SimpleDateFormat类对象加上了synchronized锁,导致同一时刻只能有一个线程执行parse(String)方法。此时,会影响程序的执行性能,在要求高并发的生产环境下,此种方式也是不太推荐使用的。
Lock锁方式
Lock锁方式与synchronized锁方式实现原理相同,都是在高并发下通过JVM的锁机制来保证程序的线程安全。通过Lock锁方式解决问题的代码如下所示。
package com.liu.news.common.utils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* @author lx
* @version 1.0
* @description: 测试SimpleDateFormat的线程不安全问题
* @date 2021/8/11 8:06
*/
public class SimpleDateFormatTest01 {
//执行总次数
private static final int EXECUTE_COUNT = 1000;
//同时运行的线程数量
private static final int THREAD_COUNT = 20;
//SimpleDateFormat对象
private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
//Lock对象
private static Lock lock = new ReentrantLock();
public static void main(String[] args) throws InterruptedException {
final Semaphore semaphore = new Semaphore(THREAD_COUNT);
final CountDownLatch countDownLatch = new CountDownLatch(EXECUTE_COUNT);
ExecutorService executorService = Executors.newCachedThreadPool();
for (int i = 0; i < EXECUTE_COUNT; i++){
executorService.execute(() -> {
try {
semaphore.acquire();
try {
// SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
// synchronized (simpleDateFormat) {
lock.lock();
Date date = simpleDateFormat.parse("2021-08-01");
System.out.println(date);
// }
} catch (ParseException e) {
System.out.println("线程:" + Thread.currentThread().getName() + " 格式化日期失败");
e.printStackTrace();
System.exit(1);
}catch (NumberFormatException e){
System.out.println("线程:" + Thread.currentThread().getName() + " 格式化日期失败");
e.printStackTrace();
System.exit(1);
}
finally {
lock.unlock();
}
semaphore.release();
} catch (InterruptedException e) {
System.out.println("信号量发生错误");
e.printStackTrace();
System.exit(1);
}
countDownLatch.countDown();
});
}
countDownLatch.await();
executorService.shutdown();
System.out.println("所有线程格式化日期成功");
}
}
通过代码可以得知,首先,定义了一个Lock类型的全局静态变量作为加锁和释放锁的句柄。然后在simpleDateFormat.parse(String)代码之前通过lock.lock()加锁。这里需要注意的一点是:为防止程序抛出异常而导致锁不能被释放,一定要将释放锁的操作放到finally代码块中
此种方式同样会影响高并发场景下的性能,不太建议在高并发的生产环境使用。
ThreadLocal方式
使用ThreadLocal存储每个线程拥有的SimpleDateFormat对象的副本,能够有效的避免多线程造成的线程安全问题,使用ThreadLocal解决线程安全问题的代码如下所示。
package com.liu.news.common.utils;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
/**
* @author lx
* @version 1.0
* @description: 测试SimpleDateFormat的线程不安全问题
* @date 2021/8/11 8:06
*/
public class SimpleDateFormatTest01 {
//执行总次数
private static final int EXECUTE_COUNT = 1000;
//同时运行的线程数量
private static final int THREAD_COUNT = 20;
//SimpleDateFormat对象
// private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
//Lock对象
// private static Lock lock = new ReentrantLock();
private static ThreadLocal<DateFormat> threadLocal = new ThreadLocal<DateFormat>(){
@Override
protected DateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd");
}
};
public static void main(String[] args) throws InterruptedException {
final Semaphore semaphore = new Semaphore(THREAD_COUNT);
final CountDownLatch countDownLatch = new CountDownLatch(EXECUTE_COUNT);
ExecutorService executorService = Executors.newCachedThreadPool();
for (int i = 0; i < EXECUTE_COUNT; i++){
executorService.execute(() -> {
try {
semaphore.acquire();
try {
// SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
// synchronized (simpleDateFormat) {
//lock.lock();
Date date = threadLocal.get().parse("2021-08-01");
System.out.println(date);
// }
} catch (ParseException e) {
System.out.println("线程:" + Thread.currentThread().getName() + " 格式化日期失败");
e.printStackTrace();
System.exit(1);
}catch (NumberFormatException e){
System.out.println("线程:" + Thread.currentThread().getName() + " 格式化日期失败");
e.printStackTrace();
System.exit(1);
}
/*finally {
lock.unlock();
}*/
semaphore.release();
} catch (InterruptedException e) {
System.out.println("信号量发生错误");
e.printStackTrace();
System.exit(1);
}
countDownLatch.countDown();
});
}
countDownLatch.await();
executorService.shutdown();
System.out.println("所有线程格式化日期成功");
}
}
package com.liu.news.common.utils;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
/**
* @author lx
* @version 1.0
* @description: 测试SimpleDateFormat的线程不安全问题
* @date 2021/8/11 8:06
*/
public class SimpleDateFormatTest01 {
//执行总次数
private static final int EXECUTE_COUNT = 1000;
//同时运行的线程数量
private static final int THREAD_COUNT = 20;
//SimpleDateFormat对象
// private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
//Lock对象
// private static Lock lock = new ReentrantLock();
/* private static ThreadLocal<DateFormat> threadLocal = new ThreadLocal<DateFormat>(){
@Override
protected DateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd");
}
};*/
private static ThreadLocal<DateFormat> threadLocal = new ThreadLocal<DateFormat>();
private static DateFormat getDateFormat(){
DateFormat dateFormat = threadLocal.get();
if(dateFormat == null){
dateFormat = new SimpleDateFormat("yyyy-MM-dd");
threadLocal.set(dateFormat);
}
return dateFormat;
}
public static void main(String[] args) throws InterruptedException {
final Semaphore semaphore = new Semaphore(THREAD_COUNT);
final CountDownLatch countDownLatch = new CountDownLatch(EXECUTE_COUNT);
ExecutorService executorService = Executors.newCachedThreadPool();
for (int i = 0; i < EXECUTE_COUNT; i++){
executorService.execute(() -> {
try {
semaphore.acquire();
try {
// SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
// synchronized (simpleDateFormat) {
//lock.lock();
Date date = getDateFormat().parse("2021-08-01");
System.out.println(date);
// }
} catch (ParseException e) {
System.out.println("线程:" + Thread.currentThread().getName() + " 格式化日期失败");
e.printStackTrace();
System.exit(1);
}catch (NumberFormatException e){
System.out.println("线程:" + Thread.currentThread().getName() + " 格式化日期失败");
e.printStackTrace();
System.exit(1);
}
/*finally {
lock.unlock();
}*/
semaphore.release();
} catch (InterruptedException e) {
System.out.println("信号量发生错误");
e.printStackTrace();
System.exit(1);
}
countDownLatch.countDown();
});
}
countDownLatch.await();
executorService.shutdown();
System.out.println("所有线程格式化日期成功");
}
}
通过代码可以得知,将每个线程使用的SimpleDateFormat副本保存在ThreadLocal中,各个线程在使用时互不干扰,从而解决了线程安全问题。
此种方式运行效率比较高,推荐在高并发业务场景的生产环境使用。
DateTimeFormatter方式
DateTimeFormatter是Java8提供的新的日期时间API中的类,DateTimeFormatter类是线程安全的,可以在高并发场景下直接使用DateTimeFormatter类来处理日期的格式化操作。代码如下所示。
package com.liu.news.common.utils;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
/**
* @author lx
* @version 1.0
* @description: 测试SimpleDateFormat的线程不安全问题
* @date 2021/8/11 8:06
*/
public class SimpleDateFormatTest01 {
//执行总次数
private static final int EXECUTE_COUNT = 1000;
//同时运行的线程数量
private static final int THREAD_COUNT = 20;
//SimpleDateFormat对象
// private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
//Lock对象
// private static Lock lock = new ReentrantLock();
/* private static ThreadLocal<DateFormat> threadLocal = new ThreadLocal<DateFormat>(){
@Override
protected DateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd");
}
};*/
// private static ThreadLocal<DateFormat> threadLocal = new ThreadLocal<DateFormat>();
/* private static DateFormat getDateFormat(){
DateFormat dateFormat = threadLocal.get();
if(dateFormat == null){
dateFormat = new SimpleDateFormat("yyyy-MM-dd");
threadLocal.set(dateFormat);
}
return dateFormat;
}*/
private static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
public static void main(String[] args) throws InterruptedException {
final Semaphore semaphore = new Semaphore(THREAD_COUNT);
final CountDownLatch countDownLatch = new CountDownLatch(EXECUTE_COUNT);
ExecutorService executorService = Executors.newCachedThreadPool();
for (int i = 0; i < EXECUTE_COUNT; i++){
executorService.execute(() -> {
try {
semaphore.acquire();
try {
// SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
// synchronized (simpleDateFormat) {
//lock.lock();
// Date date = getDateFormat().parse("2021-08-01");
LocalDate date = LocalDate.parse("2021-08-01", formatter);
System.out.println(date);
// }
} catch (Exception e){
System.out.println("线程:" + Thread.currentThread().getName() + " 格式化日期失败");
e.printStackTrace();
System.exit(1);
}
/*finally {
lock.unlock();
}*/
semaphore.release();
} catch (InterruptedException e) {
System.out.println("信号量发生错误");
e.printStackTrace();
System.exit(1);
}
countDownLatch.countDown();
});
}
countDownLatch.await();
executorService.shutdown();
System.out.println("所有线程格式化日期成功");
}
}
DateTimeFormatter类是线程安全的,可以在高并发场景下直接使用DateTimeFormatter类来处理日期的格式化操作。
使用DateTimeFormatter类来处理日期的格式化操作运行效率比较高,推荐在高并发业务场景的生产环境使用。
joda-time方式
joda-time是第三方处理日期时间格式化的类库,是线程安全的。如果使用joda-time来处理日期和时间的格式化,则需要引入第三方类库。这里,以Maven为例,如下所示引入joda-time库。
joda-time
joda-time
2.9.9
package com.liu.news.common.utils;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
/**
* @author lx
* @version 1.0
* @description: 测试SimpleDateFormat的线程不安全问题
* @date 2021/8/11 8:06
*/
public class SimpleDateFormatTest01 {
//执行总次数
private static final int EXECUTE_COUNT = 1000;
//同时运行的线程数量
private static final int THREAD_COUNT = 20;
//SimpleDateFormat对象
// private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
//Lock对象
// private static Lock lock = new ReentrantLock();
/* private static ThreadLocal<DateFormat> threadLocal = new ThreadLocal<DateFormat>(){
@Override
protected DateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd");
}
};*/
// private static ThreadLocal<DateFormat> threadLocal = new ThreadLocal<DateFormat>();
/* private static DateFormat getDateFormat(){
DateFormat dateFormat = threadLocal.get();
if(dateFormat == null){
dateFormat = new SimpleDateFormat("yyyy-MM-dd");
threadLocal.set(dateFormat);
}
return dateFormat;
}*/
//private static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
private static DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd");
public static void main(String[] args) throws InterruptedException {
final Semaphore semaphore = new Semaphore(THREAD_COUNT);
final CountDownLatch countDownLatch = new CountDownLatch(EXECUTE_COUNT);
ExecutorService executorService = Executors.newCachedThreadPool();
for (int i = 0; i < EXECUTE_COUNT; i++){
executorService.execute(() -> {
try {
semaphore.acquire();
try {
// SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
// synchronized (simpleDateFormat) {
//lock.lock();
// Date date = getDateFormat().parse("2021-08-01");
Date date = DateTime.parse("2021-08-01", dateTimeFormatter).toDate();
System.out.println(date);
// }
} catch (Exception e){
System.out.println("线程:" + Thread.currentThread().getName() + " 格式化日期失败");
e.printStackTrace();
System.exit(1);
}
/*finally {
lock.unlock();
}*/
semaphore.release();
} catch (InterruptedException e) {
System.out.println("信号量发生错误");
e.printStackTrace();
System.exit(1);
}
countDownLatch.countDown();
});
}
countDownLatch.await();
executorService.shutdown();
System.out.println("所有线程格式化日期成功");
}
}
DateTime类是org.joda.time包下的类,DateTimeFormat类和DateTimeFormatter类都是org.joda.time.format包下的类
使用joda-time库来处理日期的格式化操作运行效率比较高,推荐在高并发业务场景的生产环境使用。
解决SimpleDateFormat类的线程安全问题的方案总结
综上所示:在解决解决SimpleDateFormat类的线程安全问题的几种方案中,局部变量法由于线程每次执行格式化时间时,都会创建SimpleDateFormat类的对象,这会导致创建大量的SimpleDateFormat对象,浪费运行空间和消耗服务器的性能,因为JVM创建和销毁对象是要耗费性能的。所以,不推荐在高并发要求的生产环境使用。
synchronized锁方式和Lock锁方式在处理问题的本质上是一致的,通过加锁的方式,使同一时刻只能有一个线程执行格式化日期和时间的操作。这种方式虽然减少了SimpleDateFormat对象的创建,但是由于同步锁的存在,导致性能下降,所以,不推荐在高并发要求的生产环境使用。
ThreadLocal通过保存各个线程的SimpleDateFormat类对象的副本,使每个线程在运行时,各自使用自身绑定的SimpleDateFormat对象,互不干扰,执行性能比较高,推荐在高并发的生产环境使用。
DateTimeFormatter是Java 8中提供的处理日期和时间的类,DateTimeFormatter类本身就是线程安全的,经压测,DateTimeFormatter类处理日期和时间的性能效果还不错。所以,推荐在高并发场景下的生产环境使用。
joda-time是第三方处理日期和时间的类库,线程安全,性能经过高并发的考验,推荐在高并发场景下的生产环境使用。