还在用 SimpleDateFormat 做时间格式化?小心项目崩掉!

2023-10-15 10:10

本文主要是介绍还在用 SimpleDateFormat 做时间格式化?小心项目崩掉!,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Hollis的新书限时折扣中,一本深入讲解Java基础的干货笔记!

来源:blog.csdn.net/QiuHaoqian/article/details/116594422

今天聊聊 SimpleDateFormat 在多线程环境下存在线程安全问题。

1 SimpleDateFormat.parse() 方法的线程安全问题

1.1 错误示例

错误使用SimpleDateFormat.parse()的代码如下:

import java.text.SimpleDateFormat;public class SimpleDateFormatTest {private static final SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");public static void main(String[] args) {/*** SimpleDateFormat线程不安全,没有保证线程安全(没有加锁)的情况下,禁止使用全局SimpleDateFormat,否则报错 NumberFormatException** private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");*/for (int i = 0; i < 20; ++i) {Thread thread = new Thread(() -> {try {// 错误写法会导致线程安全问题System.out.println(Thread.currentThread().getName() + "--" + SIMPLE_DATE_FORMAT.parse("2020-06-01 11:35:00"));} catch (Exception e) {e.printStackTrace();}}, "Thread-" + i);thread.start();}}
}

报错:

44127261a7b40b90aa521633cc2a86f4.png

1.2 非线程安全原因分析

查看源码中可以看到:SimpleDateFormat继承DateFormat类,SimpleDateFormat转换日期是通过继承自DateFormat类的Calendar对象来操作的,Calendar对象会被用来进行日期-时间计算,既被用于format方法也被用于parse方法。

0cdab0848e63b4192970c9db00671e06.png

SimpleDateFormat 的 parse(String source) 方法 会调用继承自父类的 DateFormat 的 parse(String source) 方法

4bddd1773e91a4bd704427cb2311e7e7.png

DateFormat 的 parse(String source) 方法会调用SimpleDateFormat中重写的 parse(String text, ParsePosition pos) 方法,该方法中有个地方需要关注

bba5da482a9b4f3c037f9f496ad7c9f1.png

SimpleDateFormat 中重写的 parse(String text, ParsePosition pos) 方法中调用了 establish(calendar) 这个方法:

651dd5acb2a84ed497d0dbeb6306fa11.png

该方法中调用了 Calendar 的 clear() 方法

e18b258118fa0246388183c90b10f424.png

可以发现整个过程中Calendar对象它并不是线程安全的,如果,a线程将calendar清空了,calendar 就没有新值了,恰好此时b线程刚好进入到parse方法用到了calendar对象,那就会产生线程安全问题了!

正常情况下:

83be0bee39ac15a10a5c55a3f54dcdaf.png

非线程安全的流程:

283354d39c4dbe41dfc4f06c7485eba0.png

1.3 解决方法

方法1:每个线程都new一个SimpleDateFormat

import java.text.SimpleDateFormat;public class SimpleDateFormatTest {public static void main(String[] args) {for (int i = 0; i < 20; ++i) {Thread thread = new Thread(() -> {try {// 每个线程都new一个SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");System.out.println(Thread.currentThread().getName() + "--" + simpleDateFormat.parse("2020-06-01 11:35:00"));} catch (Exception e) {e.printStackTrace();}}, "Thread-" + i);thread.start();}}
}

方式2:synchronized等方式加锁

public class SimpleDateFormatTest {private static final SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");public static void main(String[] args) {for (int i = 0; i < 20; ++i) {Thread thread = new Thread(() -> {try {synchronized (SIMPLE_DATE_FORMAT) {System.out.println(Thread.currentThread().getName() + "--" + SIMPLE_DATE_FORMAT.parse("2020-06-01 11:35:00"));}} catch (Exception e) {e.printStackTrace();}}, "Thread-" + i);thread.start();}}
}

方式3:使用ThreadLocal 为每个线程创建一个独立变量

import java.text.DateFormat;
import java.text.SimpleDateFormat;public class SimpleDateFormatTest {private static final ThreadLocal<DateFormat> SAFE_SIMPLE_DATE_FORMAT = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));public static void main(String[] args) {for (int i = 0; i < 20; ++i) {Thread thread = new Thread(() -> {try {System.out.println(Thread.currentThread().getName() + "--" + SAFE_SIMPLE_DATE_FORMAT.get().parse("2020-06-01 11:35:00"));} catch (Exception e) {e.printStackTrace();}}, "Thread-" + i);thread.start();}}
}

2 SimpleDateFormat.format() 方法的线程安全问题

2.1 错误示例

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;public class SimpleDateFormatTest {// 时间格式化对象private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("mm:ss");public static void main(String[] args) throws InterruptedException {// 创建线程池执行任务ThreadPoolExecutor threadPool = new ThreadPoolExecutor(10, 10, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<>(1000));for (int i = 0; i < 1000; i++) {int finalI = i;// 执行任务threadPool.execute(new Runnable() {@Overridepublic void run() {Date date = new Date(finalI * 1000); // 得到时间对象formatAndPrint(date); // 执行时间格式化}});}threadPool.shutdown(); // 线程池执行完任务之后关闭}/*** 格式化并打印时间*/private static void formatAndPrint(Date date) {String result = simpleDateFormat.format(date); // 执行格式化System.out.println("时间:" + result); // 打印最终结果}
}

c19a46d1cda268b7bc1d5e7a78ba488b.png

从上述结果可以看出,程序的打印结果竟然有重复内容的,正确的情况应该是没有重复的时间才对。

2.2 非线程安全原因分析

为了找到问题所在,查看 SimpleDateFormat 中 format 方法的源码来排查一下问题,format 源码如下:

694bb739b696d1e090f80034e83b1b44.png

从上述源码可以看出,在执行 SimpleDateFormat.format() 方法时,会使用 calendar.setTime() 方法将输入的时间进行转换,那么我们想想一下这样的场景:

  • 线程 1 执行了 calendar.setTime(date) 方法,将用户输入的时间转换成了后面格式化时所需要的时间;

  • 线程 1 暂停执行,线程 2 得到 CPU 时间片开始执行;

  • 线程 2 执行了 calendar.setTime(date) 方法,对时间进行了修改;

  • 线程 2 暂停执行,线程 1 得出 CPU 时间片继续执行,因为线程 1 和线程 2 使用的是同一对象,而时间已经被线程 2 修改了,所以此时当线程 1 继续执行的时候就会出现线程安全的问题了。

正常的情况下,程序的执行是这样的:

fd4b4b4d54acf72efad44866bdfd1f0e.png

非线程安全的执行流程是这样的:

e15e04533459e282c851a434b5ed60f1.png

2.3 解决方法

同样有三种解决方法

方法1:每个线程都new一个SimpleDateFormat

public class SimpleDateFormatTest {public static void main(String[] args) throws InterruptedException {// 创建线程池执行任务ThreadPoolExecutor threadPool = new ThreadPoolExecutor(10, 10, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<>(1000));for (int i = 0; i < 1000; i++) {int finalI = i;// 执行任务threadPool.execute(new Runnable() {@Overridepublic void run() {// 得到时间对象Date date = new Date(finalI * 1000);// 执行时间格式化formatAndPrint(date);}});}// 线程池执行完任务之后关闭threadPool.shutdown();}/*** 格式化并打印时间*/private static void formatAndPrint(Date date) {String result = new SimpleDateFormat("mm:ss").format(date); // 执行格式化System.out.println("时间:" + result); // 打印最终结果}
}

方式2:synchronized等方式加锁

所有的线程必须排队执行某些业务才行,这样无形中就降低了程序的运行效率了

public class SimpleDateFormatTest {// 时间格式化对象private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("mm:ss");public static void main(String[] args) throws InterruptedException {// 创建线程池执行任务ThreadPoolExecutor threadPool = new ThreadPoolExecutor(10, 10, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<>(1000));for (int i = 0; i < 1000; i++) {int finalI = i;// 执行任务threadPool.execute(new Runnable() {@Overridepublic void run() {Date date = new Date(finalI * 1000); // 得到时间对象formatAndPrint(date); // 执行时间格式化}});}// 线程池执行完任务之后关闭threadPool.shutdown();}/*** 格式化并打印时间*/private static void formatAndPrint(Date date) {// 执行格式化String result = null;// 加锁synchronized (SimpleDateFormatTest.class) {result = simpleDateFormat.format(date);}// 打印最终结果System.out.println("时间:" + result);}
}

方式3:使用ThreadLocal 为每个线程创建一个独立变量

public class SimpleDateFormatTest {// 创建 ThreadLocal 并设置默认值private static ThreadLocal<SimpleDateFormat> dateFormatThreadLocal =ThreadLocal.withInitial(() -> new SimpleDateFormat("mm:ss"));public static void main(String[] args) {// 创建线程池执行任务ThreadPoolExecutor threadPool = new ThreadPoolExecutor(10, 10, 60,TimeUnit.SECONDS, new LinkedBlockingQueue<>(1000));// 执行任务for (int i = 0; i < 1000; i++) {int finalI = i;// 执行任务threadPool.execute(() -> {Date date = new Date(finalI * 1000); // 得到时间对象formatAndPrint(date); // 执行时间格式化});}threadPool.shutdown(); // 线程池执行完任务之后关闭}/*** 格式化并打印时间*/private static void formatAndPrint(Date date) {String result = dateFormatThreadLocal.get().format(date); // 执行格式化System.out.println("时间:" + result);  // 打印最终结果}
}

我的新书《深入理解Java核心技术》已经上市了,上市后一直蝉联京东畅销榜中,目前正在6折优惠中,想要入手的朋友千万不要错过哦~长按二维码即可购买~

9852b353f58d809484dea7638dc4f97b.png

长按扫码享受6折优惠

往期推荐

12422939a0924c1cf89a26a8ed69d1c2.png

入职一家新公司,如何快速熟悉代码?


2be001c3661bbcba46a8cd197b06b805.png

揭秘:春晚微信红包,是如何抗住 100 亿次请求的?


556d1acdec6151952280f3d1b0309245.png

你还不明白如何解决分布式Session?看这篇就够了!


如果你喜欢本文,

请长按二维码,关注 Hollis.

08d1c08a8057a54614f05a71575d8bc5.png

转发至朋友圈,是对我最大的支持。

点个 在看 

喜欢是一种感觉

在看是一种支持

↘↘↘

这篇关于还在用 SimpleDateFormat 做时间格式化?小心项目崩掉!的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/216986

相关文章

部署Vue项目到服务器后404错误的原因及解决方案

《部署Vue项目到服务器后404错误的原因及解决方案》文章介绍了Vue项目部署步骤以及404错误的解决方案,部署步骤包括构建项目、上传文件、配置Web服务器、重启Nginx和访问域名,404错误通常是... 目录一、vue项目部署步骤二、404错误原因及解决方案错误场景原因分析解决方案一、Vue项目部署步骤

golang内存对齐的项目实践

《golang内存对齐的项目实践》本文主要介绍了golang内存对齐的项目实践,内存对齐不仅有助于提高内存访问效率,还确保了与硬件接口的兼容性,是Go语言编程中不可忽视的重要优化手段,下面就来介绍一下... 目录一、结构体中的字段顺序与内存对齐二、内存对齐的原理与规则三、调整结构体字段顺序优化内存对齐四、内

如何利用Java获取当天的开始和结束时间

《如何利用Java获取当天的开始和结束时间》:本文主要介绍如何使用Java8的LocalDate和LocalDateTime类获取指定日期的开始和结束时间,展示了如何通过这些类进行日期和时间的处... 目录前言1. Java日期时间API概述2. 获取当天的开始和结束时间代码解析运行结果3. 总结前言在J

配置springboot项目动静分离打包分离lib方式

《配置springboot项目动静分离打包分离lib方式》本文介绍了如何将SpringBoot工程中的静态资源和配置文件分离出来,以减少jar包大小,方便修改配置文件,通过在jar包同级目录创建co... 目录前言1、分离配置文件原理2、pom文件配置3、使用package命令打包4、总结前言默认情况下,

修改若依框架Token的过期时间问题

《修改若依框架Token的过期时间问题》本文介绍了如何修改若依框架中Token的过期时间,通过修改`application.yml`文件中的配置来实现,默认单位为分钟,希望此经验对大家有所帮助,也欢迎... 目录修改若依框架Token的过期时间修改Token的过期时间关闭Token的过期时js间总结修改若依

Go Mongox轻松实现MongoDB的时间字段自动填充

《GoMongox轻松实现MongoDB的时间字段自动填充》这篇文章主要为大家详细介绍了Go语言如何使用mongox库,在插入和更新数据时自动填充时间字段,从而提升开发效率并减少重复代码,需要的可以... 目录前言时间字段填充规则Mongox 的安装使用 Mongox 进行插入操作使用 Mongox 进行更

springboot日期格式化全局LocalDateTime详解

《springboot日期格式化全局LocalDateTime详解》文章主要分析了SpringBoot中ObjectMapper对象的序列化和反序列化过程,并具体探讨了日期格式化问题,通过分析Spri... 目录分析ObjectMapper与jsonSerializer结论自定义日期格式(全局)扩展利用配置

python实现简易SSL的项目实践

《python实现简易SSL的项目实践》本文主要介绍了python实现简易SSL的项目实践,包括CA.py、server.py和client.py三个模块,文中通过示例代码介绍的非常详细,对大家的学习... 目录运行环境运行前准备程序实现与流程说明运行截图代码CA.pyclient.pyserver.py参

IDEA运行spring项目时,控制台未出现的解决方案

《IDEA运行spring项目时,控制台未出现的解决方案》文章总结了在使用IDEA运行代码时,控制台未出现的问题和解决方案,问题可能是由于点击图标或重启IDEA后控制台仍未显示,解决方案提供了解决方法... 目录问题分析解决方案总结问题js使用IDEA,点击运行按钮,运行结束,但控制台未出现http://

对postgresql日期和时间的比较

《对postgresql日期和时间的比较》文章介绍了在数据库中处理日期和时间类型时的一些注意事项,包括如何将字符串转换为日期或时间类型,以及在比较时自动转换的情况,作者建议在使用数据库时,根据具体情况... 目录PostgreSQL日期和时间比较DB里保存到时分秒,需要和年月日比较db里存储date或者ti