JUC:SimpleDateFormat的线程安全问题 以及 不可变类型DateTimeFormatter的使用

本文主要是介绍JUC:SimpleDateFormat的线程安全问题 以及 不可变类型DateTimeFormatter的使用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

文章目录

  • 不可变类
    • SimpleDateFormat
      • 为什么不安全?
      • 解决
    • 不可变类保证线程安全的实现

不可变类

SimpleDateFormat

    public static void main(String[] args) {SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");for (int i = 0; i < 100; i++) {new Thread(() -> {try {System.out.println(simpleDateFormat.parse("1951-04-21"));} catch (ParseException e) {e.printStackTrace();}}).start();}}

SimpleDateFormat是一个线程不安全的,多线程下大概率出现报错:
在这里插入图片描述

为什么不安全?

来看看这个方法:

    @Overridepublic Date parse(String text, ParsePosition pos){checkNegativeNumberExpression();int start = pos.index;int oldStart = start;int textLength = text.length();boolean[] ambiguousYear = {false};CalendarBuilder calb = new CalendarBuilder();for (int i = 0; i < compiledPattern.length; ) {int tag = compiledPattern[i] >>> 8;int count = compiledPattern[i++] & 0xff;if (count == 255) {count = compiledPattern[i++] << 16;count |= compiledPattern[i++];}switch (tag) {case TAG_QUOTE_ASCII_CHAR:if (start >= textLength || text.charAt(start) != (char)count) {pos.index = oldStart;pos.errorIndex = start;return null;}start++;break;case TAG_QUOTE_CHARS:while (count-- > 0) {if (start >= textLength || text.charAt(start) != compiledPattern[i++]) {pos.index = oldStart;pos.errorIndex = start;return null;}start++;}break;default:// Peek the next pattern to determine if we need to// obey the number of pattern letters for// parsing. It's required when parsing contiguous// digit text (e.g., "20010704") with a pattern which// has no delimiters between fields, like "yyyyMMdd".boolean obeyCount = false;// In Arabic, a minus sign for a negative number is put after// the number. Even in another locale, a minus sign can be// put after a number using DateFormat.setNumberFormat().// If both the minus sign and the field-delimiter are '-',// subParse() needs to determine whether a '-' after a number// in the given text is a delimiter or is a minus sign for the// preceding number. We give subParse() a clue based on the// information in compiledPattern.boolean useFollowingMinusSignAsDelimiter = false;if (i < compiledPattern.length) {int nextTag = compiledPattern[i] >>> 8;if (!(nextTag == TAG_QUOTE_ASCII_CHAR ||nextTag == TAG_QUOTE_CHARS)) {obeyCount = true;}if (hasFollowingMinusSign &&(nextTag == TAG_QUOTE_ASCII_CHAR ||nextTag == TAG_QUOTE_CHARS)) {int c;if (nextTag == TAG_QUOTE_ASCII_CHAR) {c = compiledPattern[i] & 0xff;} else {c = compiledPattern[i+1];}if (c == minusSign) {useFollowingMinusSignAsDelimiter = true;}}}start = subParse(text, start, tag, count, obeyCount,ambiguousYear, pos,useFollowingMinusSignAsDelimiter, calb);if (start < 0) {pos.index = oldStart;return null;}}}// At this point the fields of Calendar have been set.  Calendar// will fill in default values for missing fields when the time// is computed.pos.index = start;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();}}}// An IllegalArgumentException will be thrown by Calendar.getTime()// if any fields are out of range, e.g., MONTH == 17.catch (IllegalArgumentException e) {pos.errorIndex = start;pos.index = oldStart;return null;}return parsedDate;}

在这里插入图片描述

主要是这里调用了establish()

  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;}}}if (weekDate) {int weekOfYear = isSet(WEEK_OF_YEAR) ? field[MAX_FIELD + WEEK_OF_YEAR] : 1;int dayOfWeek = isSet(DAY_OF_WEEK) ?field[MAX_FIELD + DAY_OF_WEEK] : cal.getFirstDayOfWeek();if (!isValidDayOfWeek(dayOfWeek) && cal.isLenient()) {if (dayOfWeek >= 8) {dayOfWeek--;weekOfYear += dayOfWeek / 7;dayOfWeek = (dayOfWeek % 7) + 1;} else {while (dayOfWeek <= 0) {dayOfWeek += 7;weekOfYear--;}}dayOfWeek = toCalendarDayOfWeek(dayOfWeek);}cal.setWeekDate(field[MAX_FIELD + WEEK_YEAR], weekOfYear, dayOfWeek);}return cal;}

在这里插入图片描述

参数为calender,那么这个canlender出自哪里呢?
在这里插入图片描述

实际上是继承DateFormat里的。

establish中先进行了cal.clear(),又进行了cal.set()。 先清除cal对象中是值,再设置新的值。

这样多线程下,调用同一个cal,而cal又没有设置线程安全,比如线程t1刚set完,t2进行了clear,那t1的输出肯定是不对的。

下面介绍几种解决方法。

解决

方法一
首先想到的肯定是加锁

public class test10 {public static void main(String[] args) {SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");for (int i = 0; i < 100; i++) {new Thread(() -> {synchronized (simpleDateFormat) {try {System.out.println(simpleDateFormat.parse("1951-04-21"));} catch (ParseException e) {e.printStackTrace();}}}).start();}}
}

在这里插入图片描述

这样可以解决,但是效率肯定是不高的。

方法二

利用不可变类型DateTimeFormatter
源码介绍是一个不可变的、线程安全的类
在这里插入图片描述

public class test10 {public static void main(String[] args) {DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");for (int i = 0; i < 100; i++) {new Thread(() -> {TemporalAccessor parse = dateTimeFormatter.parse("1951-04-21");System.out.println(parse);}).start();}}
}

在这里插入图片描述

不可变类保证线程安全的实现

不可变类的类,属性都是final修饰的。
例如String:

在这里插入图片描述

保证只读和防止修改。

同时其方法都是操作一个新对象,并不在原对象上操作,保证了安全。
之前String都介绍过,这里就不再给出了,可以自己看看String的方法源码。
参考:
https://zhuanlan.zhihu.com/p/395751163

这篇关于JUC:SimpleDateFormat的线程安全问题 以及 不可变类型DateTimeFormatter的使用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

使用Python实现IP地址和端口状态检测与监控

《使用Python实现IP地址和端口状态检测与监控》在网络运维和服务器管理中,IP地址和端口的可用性监控是保障业务连续性的基础需求,本文将带你用Python从零打造一个高可用IP监控系统,感兴趣的小伙... 目录概述:为什么需要IP监控系统使用步骤说明1. 环境准备2. 系统部署3. 核心功能配置系统效果展

解决IDEA报错:编码GBK的不可映射字符问题

《解决IDEA报错:编码GBK的不可映射字符问题》:本文主要介绍解决IDEA报错:编码GBK的不可映射字符问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录IDEA报错:编码GBK的不可映射字符终端软件问题描述原因分析解决方案方法1:将命令改为方法2:右下jav

使用Java将各种数据写入Excel表格的操作示例

《使用Java将各种数据写入Excel表格的操作示例》在数据处理与管理领域,Excel凭借其强大的功能和广泛的应用,成为了数据存储与展示的重要工具,在Java开发过程中,常常需要将不同类型的数据,本文... 目录前言安装免费Java库1. 写入文本、或数值到 Excel单元格2. 写入数组到 Excel表格

redis中使用lua脚本的原理与基本使用详解

《redis中使用lua脚本的原理与基本使用详解》在Redis中使用Lua脚本可以实现原子性操作、减少网络开销以及提高执行效率,下面小编就来和大家详细介绍一下在redis中使用lua脚本的原理... 目录Redis 执行 Lua 脚本的原理基本使用方法使用EVAL命令执行 Lua 脚本使用EVALSHA命令

Java 中的 @SneakyThrows 注解使用方法(简化异常处理的利与弊)

《Java中的@SneakyThrows注解使用方法(简化异常处理的利与弊)》为了简化异常处理,Lombok提供了一个强大的注解@SneakyThrows,本文将详细介绍@SneakyThro... 目录1. @SneakyThrows 简介 1.1 什么是 Lombok?2. @SneakyThrows

MyBatis模糊查询报错:ParserException: not supported.pos 问题解决

《MyBatis模糊查询报错:ParserException:notsupported.pos问题解决》本文主要介绍了MyBatis模糊查询报错:ParserException:notsuppo... 目录问题描述问题根源错误SQL解析逻辑深层原因分析三种解决方案方案一:使用CONCAT函数(推荐)方案二:

使用Python和Pyecharts创建交互式地图

《使用Python和Pyecharts创建交互式地图》在数据可视化领域,创建交互式地图是一种强大的方式,可以使受众能够以引人入胜且信息丰富的方式探索地理数据,下面我们看看如何使用Python和Pyec... 目录简介Pyecharts 简介创建上海地图代码说明运行结果总结简介在数据可视化领域,创建交互式地

Redis 热 key 和大 key 问题小结

《Redis热key和大key问题小结》:本文主要介绍Redis热key和大key问题小结,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录一、什么是 Redis 热 key?热 key(Hot Key)定义: 热 key 常见表现:热 key 的风险:二、

Java Stream流使用案例深入详解

《JavaStream流使用案例深入详解》:本文主要介绍JavaStream流使用案例详解,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录前言1. Lambda1.1 语法1.2 没参数只有一条语句或者多条语句1.3 一个参数只有一条语句或者多

Java Spring 中 @PostConstruct 注解使用原理及常见场景

《JavaSpring中@PostConstruct注解使用原理及常见场景》在JavaSpring中,@PostConstruct注解是一个非常实用的功能,它允许开发者在Spring容器完全初... 目录一、@PostConstruct 注解概述二、@PostConstruct 注解的基本使用2.1 基本代