SimpleDateFormat为什么是线程不安全的?

2024-02-20 09:04

本文主要是介绍SimpleDateFormat为什么是线程不安全的?,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

在这里插入图片描述

目录

      • 在日常开发中,Date工具类使用频率相对较高,大家通常都会这样写:
      • 这很简单啊,有什么争议吗?
      • 格式化后出现的时间错乱。
      • 看看Java 8是如何解决时区问题的:
      • 在处理带时区的国际化时间问题,推荐使用jdk8的日期时间类:
      • 在与前端联调时,报了个错,```java.lang.NumberFormatException: multiple points```,起初我以为是时间格式传的不对,仔细一看,不对啊。
      • 看一下```SimpleDateFormat.parse```的源码:

大家好,我是哪吒。

在日常开发中,Date工具类使用频率相对较高,大家通常都会这样写:

public static Date getData(String date) throws ParseException {SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");return sdf.parse(date);
}public static Date getDataByFormat(String date, String format) throws ParseException {SimpleDateFormat sdf = new SimpleDateFormat(format);return sdf.parse(date);
}

这很简单啊,有什么争议吗?

你应该听过“时区”这个名词,大家也都知道,相同时刻不同时区的时间是不一样的。

因此在使用时间时,一定要给出时区信息。

public static void getDataByZone(String param, String format) throws ParseException {SimpleDateFormat sdf = new SimpleDateFormat(format);// 默认时区解析时间表示Date date = sdf.parse(param);System.out.println(date + ":" + date.getTime());// 东京时区解析时间表示sdf.setTimeZone(TimeZone.getTimeZone("Asia/Tokyo"));Date newYorkDate = sdf.parse(param);System.out.println(newYorkDate + ":" + newYorkDate.getTime());
}public static void main(String[] args) throws ParseException {getDataByZone("2023-11-10 10:00:00","yyyy-MM-dd HH:mm:ss");
}

对于当前的上海时区和纽约时区,转化为 UTC 时间戳是不同的时间。

对于同一个本地时间的表示,不同时区的人解析得到的 UTC 时间一定是不同的,反过来不同的本地时间可能对应同一个 UTC。

在这里插入图片描述

格式化后出现的时间错乱。

public static void getDataByZoneFormat(String param, String format) throws ParseException {SimpleDateFormat sdf = new SimpleDateFormat(format);Date date = sdf.parse(param);// 默认时区格式化输出System.out.println(new SimpleDateFormat("[yyyy-MM-dd HH:mm:ss Z]").format(date));// 东京时区格式化输出TimeZone.setDefault(TimeZone.getTimeZone("Asia/Tokyo"));System.out.println(new SimpleDateFormat("[yyyy-MM-dd HH:mm:ss Z]").format(date));
}public static void main(String[] args) throws ParseException {getDataByZoneFormat("2023-11-10 10:00:00","yyyy-MM-dd HH:mm:ss");
}

我当前时区的 Offset(时差)是 +8 小时,对于 +9 小时的纽约,整整差了1个小时,北京早上 10 点对应早上东京 11 点。

在这里插入图片描述

看看Java 8是如何解决时区问题的:

Java 8 推出了新的时间日期类 ZoneId、ZoneOffset、LocalDateTime、ZonedDateTime 和 DateTimeFormatter,处理时区问题更简单清晰。

public static void getDataByZoneFormat8(String param, String format) throws ParseException {ZoneId zone = ZoneId.of("Asia/Shanghai");ZoneId tokyoZone = ZoneId.of("Asia/Tokyo");ZoneId timeZone = ZoneOffset.ofHours(2);// 格式化器DateTimeFormatter dtf = DateTimeFormatter.ofPattern(format);ZonedDateTime date = ZonedDateTime.of(LocalDateTime.parse(param, dtf), zone);// withZone设置时区DateTimeFormatter dtfz = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss Z");System.out.println(dtfz.withZone(zone).format(date));System.out.println(dtfz.withZone(tokyoZone).format(date));System.out.println(dtfz.withZone(timeZone).format(date));
}public static void main(String[] args) throws ParseException {getDataByZoneFormat8("2023-11-10 10:00:00","yyyy-MM-dd HH:mm:ss");
}
  • Asia/Shanghai对应+8,对应2023-11-10 10:00:00;
  • Asia/Tokyo对应+9,对应2023-11-10 11:00:00;
  • timeZone 是+2,所以对应2023-11-10 04:00:00;

在这里插入图片描述

在处理带时区的国际化时间问题,推荐使用jdk8的日期时间类:

  1. 通过ZoneId,定义时区;
  2. 使用ZonedDateTime保存时间;
  3. 通过withZone对DateTimeFormatter设置时区;
  4. 进行时间格式化得到本地时间;

思路比较清晰,不容易出错。

在与前端联调时,报了个错,java.lang.NumberFormatException: multiple points,起初我以为是时间格式传的不对,仔细一看,不对啊。

百度一下,才知道是高并发情况下SimpleDateFormat有线程安全的问题。

下面通过模拟高并发,把这个问题复现一下:

public static void getDataByThread(String param, String format) throws InterruptedException {ExecutorService threadPool = Executors.newFixedThreadPool(5);SimpleDateFormat sdf = new SimpleDateFormat(format);// 模拟并发环境,开启5个并发线程for (int i = 0; i < 5; i++) {threadPool.execute(() -> {for (int j = 0; j < 2; j++) {try {System.out.println(sdf.parse(param));} catch (ParseException e) {System.out.println(e);}}});}threadPool.shutdown();threadPool.awaitTermination(1, TimeUnit.HOURS);
}

果不其然,报错。还将2023年转换成2220年,我勒个乖乖。

在时间工具类里,时间格式化,我都是这样弄的啊,没问题啊,为啥这个不行?原来是因为共用了同一个SimpleDateFormat,在工具类里,一个线程一个SimpleDateFormat,当然没问题啦!

在这里插入图片描述

可以通过TreadLocal 局部变量,解决SimpleDateFormat的线程安全问题。

public static void getDataByThreadLocal(String time, String format) throws InterruptedException {ExecutorService threadPool = Executors.newFixedThreadPool(5);ThreadLocal<SimpleDateFormat> sdf = new ThreadLocal<SimpleDateFormat>() {@Overrideprotected SimpleDateFormat initialValue() {return new SimpleDateFormat(format);}};// 模拟并发环境,开启5个并发线程for (int i = 0; i < 5; i++) {threadPool.execute(() -> {for (int j = 0; j < 2; j++) {try {System.out.println(sdf.get().parse(time));} catch (ParseException e) {System.out.println(e);}}});}threadPool.shutdown();threadPool.awaitTermination(1, TimeUnit.HOURS);
}

在这里插入图片描述

看一下SimpleDateFormat.parse的源码:

public class SimpleDateFormat extends DateFormat {@Overridepublic Date parse(String text, ParsePosition pos){CalendarBuilder calb = new CalendarBuilder();Date parsedDate;try {parsedDate = calb.establish(calendar).getTime();// If the year value is ambiguous,// then the two-digit year == the default start yearif (ambiguousYear[0]) {if (parsedDate.before(defaultCenturyStart)) {parsedDate = calb.addYear(100).establish(calendar).getTime();}}}}
}class CalendarBuilder {Calendar establish(Calendar cal) {boolean weekDate = isSet(WEEK_YEAR)&& field[WEEK_YEAR] > field[YEAR];if (weekDate && !cal.isWeekDateSupported()) {// Use YEAR insteadif (!isSet(YEAR)) {set(YEAR, field[MAX_FIELD + WEEK_YEAR]);}weekDate = false;}cal.clear();// Set the fields from the min stamp to the max stamp so that// the field resolution works in the Calendar.for (int stamp = MINIMUM_USER_STAMP; stamp < nextStamp; stamp++) {for (int index = 0; index <= maxFieldIndex; index++) {if (field[index] == stamp) {cal.set(index, field[MAX_FIELD + index]);break;}}}...}
}
  1. 先new CalendarBuilder();
  2. 通过parsedDate = calb.establish(calendar).getTime();解析时间;
  3. establish方法内先cal.clear(),再重新构建cal,整个操作没有加锁;

上面几步就会导致在高并发场景下,线程1正在操作一个Calendar,此时线程2又来了。线程1还没来得及处理 Calendar 就被线程2清空了。

因此,通过编写Date工具类,一个线程一个SimpleDateFormat,还是有一定道理的。


🏆哪吒多年工作总结:Java学习路线总结,搬砖工逆袭Java架构师

华为OD机试 2023B卷题库疯狂收录中,刷题点这里

刷的越多,抽中的概率越大,每一题都有详细的答题思路、详细的代码注释、样例测试,发现新题目,随时更新,全天CSDN在线答疑。

这篇关于SimpleDateFormat为什么是线程不安全的?的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

Java中实现线程的创建和启动的方法

《Java中实现线程的创建和启动的方法》在Java中,实现线程的创建和启动是两个不同但紧密相关的概念,理解为什么要启动线程(调用start()方法)而非直接调用run()方法,是掌握多线程编程的关键,... 目录1. 线程的生命周期2. start() vs run() 的本质区别3. 为什么必须通过 st

Linux实现线程同步的多种方式汇总

《Linux实现线程同步的多种方式汇总》本文详细介绍了Linux下线程同步的多种方法,包括互斥锁、自旋锁、信号量以及它们的使用示例,通过这些同步机制,可以解决线程安全问题,防止资源竞争导致的错误,示例... 目录什么是线程同步?一、互斥锁(单人洗手间规则)适用场景:特点:二、条件变量(咖啡厅取餐系统)工作流

Java中常见队列举例详解(非线程安全)

《Java中常见队列举例详解(非线程安全)》队列用于模拟队列这种数据结构,队列通常是指先进先出的容器,:本文主要介绍Java中常见队列(非线程安全)的相关资料,文中通过代码介绍的非常详细,需要的朋... 目录一.队列定义 二.常见接口 三.常见实现类3.1 ArrayDeque3.1.1 实现原理3.1.2

SpringBoot3中使用虚拟线程的完整步骤

《SpringBoot3中使用虚拟线程的完整步骤》在SpringBoot3中使用Java21+的虚拟线程(VirtualThreads)可以显著提升I/O密集型应用的并发能力,这篇文章为大家介绍了详细... 目录1. 环境准备2. 配置虚拟线程方式一:全局启用虚拟线程(Tomcat/Jetty)方式二:异步

如何解决Druid线程池Cause:java.sql.SQLRecoverableException:IO错误:Socket read timed out的问题

《如何解决Druid线程池Cause:java.sql.SQLRecoverableException:IO错误:Socketreadtimedout的问题》:本文主要介绍解决Druid线程... 目录异常信息触发场景找到版本发布更新的说明从版本更新信息可以看到该默认逻辑已经去除总结异常信息触发场景复

JAVA保证HashMap线程安全的几种方式

《JAVA保证HashMap线程安全的几种方式》HashMap是线程不安全的,这意味着如果多个线程并发地访问和修改同一个HashMap实例,可能会导致数据不一致和其他线程安全问题,本文主要介绍了JAV... 目录1. 使用 Collections.synchronizedMap2. 使用 Concurren

Python从零打造高安全密码管理器

《Python从零打造高安全密码管理器》在数字化时代,每人平均需要管理近百个账号密码,本文将带大家深入剖析一个基于Python的高安全性密码管理器实现方案,感兴趣的小伙伴可以参考一下... 目录一、前言:为什么我们需要专属密码管理器二、系统架构设计2.1 安全加密体系2.2 密码强度策略三、核心功能实现详解

Spring Boot3虚拟线程的使用步骤详解

《SpringBoot3虚拟线程的使用步骤详解》虚拟线程是Java19中引入的一个新特性,旨在通过简化线程管理来提升应用程序的并发性能,:本文主要介绍SpringBoot3虚拟线程的使用步骤,... 目录问题根源分析解决方案验证验证实验实验1:未启用keep-alive实验2:启用keep-alive扩展建

Java终止正在运行的线程的三种方法

《Java终止正在运行的线程的三种方法》停止一个线程意味着在任务处理完任务之前停掉正在做的操作,也就是放弃当前的操作,停止一个线程可以用Thread.stop()方法,但最好不要用它,本文给大家介绍了... 目录前言1. 停止不了的线程2. 判断线程是否停止状态3. 能停止的线程–异常法4. 在沉睡中停止5

最新Spring Security实战教程之Spring Security安全框架指南

《最新SpringSecurity实战教程之SpringSecurity安全框架指南》SpringSecurity是Spring生态系统中的核心组件,提供认证、授权和防护机制,以保护应用免受各种安... 目录前言什么是Spring Security?同类框架对比Spring Security典型应用场景传统