还在用 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

相关文章

深度解析Java项目中包和包之间的联系

《深度解析Java项目中包和包之间的联系》文章浏览阅读850次,点赞13次,收藏8次。本文详细介绍了Java分层架构中的几个关键包:DTO、Controller、Service和Mapper。_jav... 目录前言一、各大包1.DTO1.1、DTO的核心用途1.2. DTO与实体类(Entity)的区别1

Golang如何对cron进行二次封装实现指定时间执行定时任务

《Golang如何对cron进行二次封装实现指定时间执行定时任务》:本文主要介绍Golang如何对cron进行二次封装实现指定时间执行定时任务问题,具有很好的参考价值,希望对大家有所帮助,如有错误... 目录背景cron库下载代码示例【1】结构体定义【2】定时任务开启【3】使用示例【4】控制台输出总结背景

如何在Spring Boot项目中集成MQTT协议

《如何在SpringBoot项目中集成MQTT协议》本文介绍在SpringBoot中集成MQTT的步骤,包括安装Broker、添加EclipsePaho依赖、配置连接参数、实现消息发布订阅、测试接口... 目录1. 准备工作2. 引入依赖3. 配置MQTT连接4. 创建MQTT配置类5. 实现消息发布与订阅

springboot项目打jar制作成镜像并指定配置文件位置方式

《springboot项目打jar制作成镜像并指定配置文件位置方式》:本文主要介绍springboot项目打jar制作成镜像并指定配置文件位置方式,具有很好的参考价值,希望对大家有所帮助,如有错误... 目录一、上传jar到服务器二、编写dockerfile三、新建对应配置文件所存放的数据卷目录四、将配置文

Go语言代码格式化的技巧分享

《Go语言代码格式化的技巧分享》在Go语言的开发过程中,代码格式化是一个看似细微却至关重要的环节,良好的代码格式化不仅能提升代码的可读性,还能促进团队协作,减少因代码风格差异引发的问题,Go在代码格式... 目录一、Go 语言代码格式化的重要性二、Go 语言代码格式化工具:gofmt 与 go fmt(一)

怎么用idea创建一个SpringBoot项目

《怎么用idea创建一个SpringBoot项目》本文介绍了在IDEA中创建SpringBoot项目的步骤,包括环境准备(JDK1.8+、Maven3.2.5+)、使用SpringInitializr... 目录如何在idea中创建一个SpringBoot项目环境准备1.1打开IDEA,点击New新建一个项

springboot项目中整合高德地图的实践

《springboot项目中整合高德地图的实践》:本文主要介绍springboot项目中整合高德地图的实践,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一:高德开放平台的使用二:创建数据库(我是用的是mysql)三:Springboot所需的依赖(根据你的需求再

一文详解如何在idea中快速搭建一个Spring Boot项目

《一文详解如何在idea中快速搭建一个SpringBoot项目》IntelliJIDEA作为Java开发者的‌首选IDE‌,深度集成SpringBoot支持,可一键生成项目骨架、智能配置依赖,这篇文... 目录前言1、创建项目名称2、勾选需要的依赖3、在setting中检查maven4、编写数据源5、开启热

SpringBoot项目配置logback-spring.xml屏蔽特定路径的日志

《SpringBoot项目配置logback-spring.xml屏蔽特定路径的日志》在SpringBoot项目中,使用logback-spring.xml配置屏蔽特定路径的日志有两种常用方式,文中的... 目录方案一:基础配置(直接关闭目标路径日志)方案二:结合 Spring Profile 按环境屏蔽关

C++ 函数 strftime 和时间格式示例详解

《C++函数strftime和时间格式示例详解》strftime是C/C++标准库中用于格式化日期和时间的函数,定义在ctime头文件中,它将tm结构体中的时间信息转换为指定格式的字符串,是处理... 目录C++ 函数 strftipythonme 详解一、函数原型二、功能描述三、格式字符串说明四、返回值五