SimpleDateFormat一定是线程不安全吗?
今天一位优秀的架构师告诉我,下面这段代码SimpleDateFormat是线程不安全的。
/**
* 将Date按格式转化成String
*
* @param date Date对象
* @param pattern 日期类型
* @return String
*/
public static String date2String(Date date, String pattern) {
if (date == null || pattern == null) {
return null;
}
return new SimpleDateFormat(pattern).format(date);
}

那么let us test!
简单介绍下我的测试方法
1.时间转字符串
2.字符串转时间
3.时间转字符串
比较第一个字符串和第二个字符是否相同。如果没有并发问题,那么第一个字符串跟第二个字符串肯定完全一样
第一种情况
一个SimpleDateFormat实例,并发执行。
private static void newSimpleDate() {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(10, 100, 1, TimeUnit.MINUTES,
new LinkedBlockingQueue<>(1000));
while (true) {
poolExecutor.execute(new Runnable() {
@Override
public void run() {
String dateString = simpleDateFormat.format(new Date());
try {
Date parseDate = simpleDateFormat.parse(dateString);
String dateString2 = simpleDateFormat.format(parseDate);
if (!dateString.equals(dateString2)) {
System.out.println(dateString.equals(dateString2));
}
} catch (ParseException e) {
e.printStackTrace();
}
}
});
}
结果:
false
false
false
false
false
false
false
说明存在线程不安全的问题。
第二种情况
每次新建一个SimpleDateFormat 对象
private static void oneSimpleDate() {
ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(10, 100, 1, TimeUnit.MINUTES,
new LinkedBlockingQueue<>(1000));
while (true) {
poolExecutor.execute(new Runnable() {
@Override
public void run() {
try {
date2String(new Date(), "yyyy-MM-dd HH:mm:ss");
} catch (ParseException e) {
e.printStackTrace();
}
}
});
}
}
public static void date2String(Date date, String pattern) throws ParseException {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
String dateString = new SimpleDateFormat(pattern).format(date);
Date parseDate = simpleDateFormat.parse(dateString);
String dateString2 = simpleDateFormat.format(parseDate);
System.out.println(dateString.equals(dateString2));
}
结果:永远为true
true
true
true
true
true
true
true
说明没有线程安全问题。
奇怪,那么SimpleDateFormat究竟有没有问题呢?
简单看一下SimpleDateFormat.format()方法。
protected Calendar calendar;
public StringBuffer format(Date date, StringBuffer toAppendTo,
FieldPosition pos)
{
pos.beginIndex = pos.endIndex = 0;
return format(date, toAppendTo, pos.getFieldDelegate());
} // Called from Format after creating a FieldDelegate
private StringBuffer format(Date date, StringBuffer toAppendTo,
FieldDelegate delegate) {
// Convert input date to time field list
calendar.setTime(date); boolean useDateFormatSymbols = useDateFormatSymbols(); 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:
toAppendTo.append((char)count);
break; case TAG_QUOTE_CHARS:
toAppendTo.append(compiledPattern, i, count);
i += count;
break; default:
subFormat(tag, count, delegate, toAppendTo, useDateFormatSymbols);
break;
}
}
return toAppendTo;
}
可以看到,多个线程之间共享变量calendar,并修改calendar。因此在多线程环境下,当多个线程同时使用相同的SimpleDateFormat对象(如static修饰)的话,如调用format方法时,多个线程会同时调用calender.setTime方法,导致time被别的线程修改,因此线程是不安全的。此外,parse方法也是线程不安全的。
SimpleDateFormat不是线程安全的,但这并不代表,它无法被线程安全的使用,当你把它作为局部变量,每次新建一个实例,或者加锁,或者采用架构师说的DateTimeFormatter都能规避这个问题。
就像hashmap,大家都知道他是线程不安全的,在jdk1.7采用头插法时,并发会出现死循环。但是你每次new hashmap对象,去put肯定不会有问题,尽管不会有人这么用,业务也不允许。
所以,这件事告诉我们,不要守着自己的教条主义,看到线程不安全的类,就觉得方法是线程不安全的,要看具体的使用场景;当然线程安全的类,也有可能是线程不安全的;架构师也不例外喔!
SimpleDateFormat一定是线程不安全吗?的更多相关文章
- 关于 SimpleDateFormat 的非线程安全问题及其解决方案
一直以来都是直接用SimpleDateFormat开发的,没想着考虑线程安全的问题,特记录下来(摘抄的): 1.问题: 先来看一段可能引起错误的代码: package test.date; impor ...
- SimpleDateFormat类的线程安全问题和解决方案
摘要:我们就一起看下在高并发下SimpleDateFormat类为何会出现安全问题,以及如何解决SimpleDateFormat类的安全问题. 本文分享自华为云社区<SimpleDateForm ...
- SimpleDateFormat使用和线程安全问题
SimpleDateFormat 是一个以国别敏感的方式格式化和分析数据的具体类. 它允许格式化 (date -> text).语法分析 (text -> date)和标准化. Simpl ...
- 为什么SimpleDateFormat不是线程安全的?
一.前言 日期的转换与格式化在项目中应该是比较常用的了,最近同事小刚出去面试实在是没想到被 SimpleDateFormat 给摆了一道... 面试官:项目中的日期转换怎么用的?SimpleDateF ...
- sdf SimpleDateFormat 不是线程安全的,
我经常用一个public static SimpleDateFormat sdf; 今天发现报“java.lang.NumberFormatException: multiple points”的异常 ...
- SimpleDateFormat 的性能和线程安全性
系统正常运行一段时间后,QA报给我一个异常: java.lang.OutOfMemoryError: GC overhead limit exceeded at java.text.DecimalFo ...
- SimpleDateFormat 的线程安全问题与解决方式
SimpleDateFormat 的线程安全问题 SimpleDateFormat 是一个以国别敏感的方式格式化和分析数据的详细类. 它同意格式化 (date -> text).语法分析 (te ...
- 转:浅谈SimpleDateFormat的线程安全问题
转自:https://blog.csdn.net/weixin_38810239/article/details/79941964 在实际项目中,我们经常需要将日期在String和Date之间做转化, ...
- SimpleDateFormat线程不安全及解决的方法
一. 为什么SimpleDateFormat不是线程安全的? Java源代码例如以下: /** * Date formats are not synchronized. * It is recomme ...
随机推荐
- 翻译:《实用的Python编程》02_05_Collections
目录 | 上一节 (2.4 序列) | 下一节 (2.6 列表推导式) 2.5 collections 模块 collections 模块为数据处理提供了许多有用的对象.本部分简要介绍其中的一些特性. ...
- python爬虫模拟登录验证码解决方案
[前言]几天研究验证码解决方案有三种吧.第一.手工输入,即保存图片后然后我们手工输入:第二.使用cookie,必须输入密码一次,获取cookie:第三.图像处理+深度学习方案,研究生也做相关课题,就用 ...
- 算法 - 链表操作思想 && case
算法 - 链表操作题目套路 前面这一篇文章主要讲链表操作时候的实操解决方式,本文从本质讲解链表操作的元信息,学完后,再也不怕链表操作题目了. 1.链表的基本操作 链表的基本操作无外乎插入,删除,遍历 ...
- 在16G笔记本上安装GaussDB 200
云主机太贵(最便宜的每月几千吧),长期如果需要GaussDB200有个功能测试或学习环境,那么性价比最高的方式还是在自己的笔记本电脑上尝试安装一个本地的数据库进行学习和功能验证. 01 安装环境信息 ...
- MySQL:逻辑库与表管理
逻辑库管理 语句 说明 CREATE DATABASE 逻辑库名; 创建逻辑库 SHOW DATABASES; 显示所有逻辑库 DROP DATABASE 逻辑库名; 删除逻辑库 USE 逻辑库名; ...
- SpringCloud组件
1.Hystrix 1.1.简介 Hystrix,英文意思是豪猪,全身是刺,看起来就不好惹,是一种保护机制. Hystrix也是Netflix公司的一款组件. 主页:https://github.co ...
- Nebula Storage 2.0 存储格式
随着 2.0 各版本的陆续发布,Nebula Graph 迎来了一系列的改动,在存储方面,影响最大的改动就是底层编码格式进行了修改.Nebula Graph 的底层存储是基于 KV 保存在 Rocks ...
- MyBatis(七):MyBatis缓存详解(一级缓存/二级缓存)
一级缓存 MyBatis一级缓存上SqlSession缓存,即在统一SqlSession中,在不执行增删改操作提交事务的前提下,对同一条数据进行多次查询时,第一次查询从数据库中查询,完成后会存入缓 ...
- 前后端分离之DRF——1
1. 作用 1. 序列化,序列化器会把模型对象转成字典,经过 response 以后变成 json 字符串 2. 反序列化,把客户端发送过来的数据,经过 request 以后变成字典,序列化器可以把字 ...
- U盘重装系统:手把手教你怎么使用U盘重装系统、清除登录密码
前言 之前讲过<不懂电脑也能自己重装系统,可视化傻瓜式一键重装系统不求人!!!>,这是针对可以正常开机的情况下直接使用浏览器功能重装系统, 那不能正常开机或者忘记密码的怎么办呢? 不慌,今 ...