SimpleDateFormat线程不安全了?这里有5种解决方案
摘要:我们知道SimpleDateFormat是线程不安全,本文会介绍多种解决方案来保证线程安全。
本文分享自华为云社区《java的SimpleDateFormat线程不安全出问题了,虚竹教你多种解决方案》,作者:小虚竹 。
场景
在java8以前,要格式化日期时间,就需要用到SimpleDateFormat。
但我们知道SimpleDateFormat是线程不安全的,处理时要特别小心,要加锁或者不能定义为static,要在方法内new出对象,再进行格式化。很麻烦,而且重复地new出对象,也加大了内存开销。
SimpleDateFormat线程为什么是线程不安全的呢?
来看看SimpleDateFormat的源码,先看format方法:
// 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);
...
}
问题就出在成员变量calendar,如果在使用SimpleDateFormat时,用static定义,那SimpleDateFormat变成了共享变量。那SimpleDateFormat中的calendar就可以被多个线程访问到。
SimpleDateFormat的parse方法也是线程不安全的:
public Date parse(String text, ParsePosition pos)
{
...
Date parsedDate;
try {
parsedDate = calb.establish(calendar).getTime();
// If the year value is ambiguous,
// then the two-digit year == the default start year
if (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;
}
由源码可知,最后是调用**parsedDate = calb.establish(calendar).getTime();**获取返回值。方法的参数是calendar,calendar可以被多个线程访问到,存在线程不安全问题。
我们再来看看**calb.establish(calendar)**的源码

calb.establish(calendar)方法先后调用了cal.clear()和cal.set(),先清理值,再设值。但是这两个操作并不是原子性的,也没有线程安全机制来保证,导致多线程并发时,可能会引起cal的值出现问题了。
验证SimpleDateFormat线程不安全
public class SimpleDateFormatDemoTest {
private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static void main(String[] args) {
//1、创建线程池
ExecutorService pool = Executors.newFixedThreadPool(5);
//2、为线程池分配任务
ThreadPoolTest threadPoolTest = new ThreadPoolTest();
for (int i = 0; i < 10; i++) {
pool.submit(threadPoolTest);
}
//3、关闭线程池
pool.shutdown();
}
static class ThreadPoolTest implements Runnable{
@Override
public void run() {
String dateString = simpleDateFormat.format(new Date());
try {
Date parseDate = simpleDateFormat.parse(dateString);
String dateString2 = simpleDateFormat.format(parseDate);
System.out.println(Thread.currentThread().getName()+" 线程是否安全: "+dateString.equals(dateString2));
} catch (Exception e) {
System.out.println(Thread.currentThread().getName()+" 格式化失败 ");
}
}
}
}

出现了两次false,说明线程是不安全的。而且还抛异常,这个就严重了。
解决方案
解决方案1:不要定义为static变量,使用局部变量
就是要使用SimpleDateFormat对象进行format或parse时,再定义为局部变量。就能保证线程安全。
public class SimpleDateFormatDemoTest1 {
public static void main(String[] args) {
//1、创建线程池
ExecutorService pool = Executors.newFixedThreadPool(5);
//2、为线程池分配任务
ThreadPoolTest threadPoolTest = new ThreadPoolTest();
for (int i = 0; i < 10; i++) {
pool.submit(threadPoolTest);
}
//3、关闭线程池
pool.shutdown();
}
static class ThreadPoolTest implements Runnable{
@Override
public void run() {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = simpleDateFormat.format(new Date());
try {
Date parseDate = simpleDateFormat.parse(dateString);
String dateString2 = simpleDateFormat.format(parseDate);
System.out.println(Thread.currentThread().getName()+" 线程是否安全: "+dateString.equals(dateString2));
} catch (Exception e) {
System.out.println(Thread.currentThread().getName()+" 格式化失败 ");
}
}
}
}

由图可知,已经保证了线程安全,但这种方案不建议在高并发场景下使用,因为会创建大量的SimpleDateFormat对象,影响性能。
解决方案2:加锁:synchronized锁和Lock锁
加synchronized锁
SimpleDateFormat对象还是定义为全局变量,然后需要调用SimpleDateFormat进行格式化时间时,再用synchronized保证线程安全。
public class SimpleDateFormatDemoTest2 {
private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static void main(String[] args) {
//1、创建线程池
ExecutorService pool = Executors.newFixedThreadPool(5);
//2、为线程池分配任务
ThreadPoolTest threadPoolTest = new ThreadPoolTest();
for (int i = 0; i < 10; i++) {
pool.submit(threadPoolTest);
}
//3、关闭线程池
pool.shutdown();
}
static class ThreadPoolTest implements Runnable{
@Override
public void run() {
try {
synchronized (simpleDateFormat){
String dateString = simpleDateFormat.format(new Date());
Date parseDate = simpleDateFormat.parse(dateString);
String dateString2 = simpleDateFormat.format(parseDate);
System.out.println(Thread.currentThread().getName()+" 线程是否安全: "+dateString.equals(dateString2));
}
} catch (Exception e) {
System.out.println(Thread.currentThread().getName()+" 格式化失败 ");
}
}
}
}

如图所示,线程是安全的。定义了全局变量SimpleDateFormat,减少了创建大量SimpleDateFormat对象的损耗。但是使用synchronized锁,
同一时刻只有一个线程能执行锁住的代码块,在高并发的情况下会影响性能。但这种方案不建议在高并发场景下使用
加Lock锁
加Lock锁和synchronized锁原理是一样的,都是使用锁机制保证线程的安全。
public class SimpleDateFormatDemoTest3 {
private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private static Lock lock = new ReentrantLock();
public static void main(String[] args) {
//1、创建线程池
ExecutorService pool = Executors.newFixedThreadPool(5);
//2、为线程池分配任务
ThreadPoolTest threadPoolTest = new ThreadPoolTest();
for (int i = 0; i < 10; i++) {
pool.submit(threadPoolTest);
}
//3、关闭线程池
pool.shutdown();
}
static class ThreadPoolTest implements Runnable{
@Override
public void run() {
try {
lock.lock();
String dateString = simpleDateFormat.format(new Date());
Date parseDate = simpleDateFormat.parse(dateString);
String dateString2 = simpleDateFormat.format(parseDate);
System.out.println(Thread.currentThread().getName()+" 线程是否安全: "+dateString.equals(dateString2));
} catch (Exception e) {
System.out.println(Thread.currentThread().getName()+" 格式化失败 ");
}finally {
lock.unlock();
}
}
}
}

由结果可知,加Lock锁也能保证线程安全。要注意的是,最后一定要释放锁,代码里在finally里增加了lock.unlock();,保证释放锁。
在高并发的情况下会影响性能。这种方案不建议在高并发场景下使用
解决方案3:使用ThreadLocal方式
使用ThreadLocal保证每一个线程有SimpleDateFormat对象副本。这样就能保证线程的安全。
public class SimpleDateFormatDemoTest4 {
private static ThreadLocal<DateFormat> threadLocal = new ThreadLocal<DateFormat>(){
@Override
protected DateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
}
};
public static void main(String[] args) {
//1、创建线程池
ExecutorService pool = Executors.newFixedThreadPool(5);
//2、为线程池分配任务
ThreadPoolTest threadPoolTest = new ThreadPoolTest();
for (int i = 0; i < 10; i++) {
pool.submit(threadPoolTest);
}
//3、关闭线程池
pool.shutdown();
}
static class ThreadPoolTest implements Runnable{
@Override
public void run() {
try {
String dateString = threadLocal.get().format(new Date());
Date parseDate = threadLocal.get().parse(dateString);
String dateString2 = threadLocal.get().format(parseDate);
System.out.println(Thread.currentThread().getName()+" 线程是否安全: "+dateString.equals(dateString2));
} catch (Exception e) {
System.out.println(Thread.currentThread().getName()+" 格式化失败 ");
}finally {
//避免内存泄漏,使用完threadLocal后要调用remove方法清除数据
threadLocal.remove();
}
}
}
}

使用ThreadLocal能保证线程安全,且效率也是挺高的。适合高并发场景使用。
解决方案4:使用DateTimeFormatter代替SimpleDateFormat
使用DateTimeFormatter代替SimpleDateFormat(DateTimeFormatter是线程安全的,java 8+支持)
DateTimeFormatter介绍 传送门:万字博文教你搞懂java源码的日期和时间相关用法
public class DateTimeFormatterDemoTest5 {
private static DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
public static void main(String[] args) {
//1、创建线程池
ExecutorService pool = Executors.newFixedThreadPool(5);
//2、为线程池分配任务
ThreadPoolTest threadPoolTest = new ThreadPoolTest();
for (int i = 0; i < 10; i++) {
pool.submit(threadPoolTest);
}
//3、关闭线程池
pool.shutdown();
}
static class ThreadPoolTest implements Runnable{
@Override
public void run() {
try {
String dateString = dateTimeFormatter.format(LocalDateTime.now());
TemporalAccessor temporalAccessor = dateTimeFormatter.parse(dateString);
String dateString2 = dateTimeFormatter.format(temporalAccessor);
System.out.println(Thread.currentThread().getName()+" 线程是否安全: "+dateString.equals(dateString2));
} catch (Exception e) {
e.printStackTrace();
System.out.println(Thread.currentThread().getName()+" 格式化失败 ");
}
}
}
}

使用DateTimeFormatter能保证线程安全,且效率也是挺高的。适合高并发场景使用。
解决方案5:使用FastDateFormat 替换SimpleDateFormat
使用FastDateFormat 替换SimpleDateFormat(FastDateFormat 是线程安全的,Apache Commons Lang包支持,不受限于java版本)
public class FastDateFormatDemo6 {
private static FastDateFormat fastDateFormat = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss");
public static void main(String[] args) {
//1、创建线程池
ExecutorService pool = Executors.newFixedThreadPool(5);
//2、为线程池分配任务
ThreadPoolTest threadPoolTest = new ThreadPoolTest();
for (int i = 0; i < 10; i++) {
pool.submit(threadPoolTest);
}
//3、关闭线程池
pool.shutdown();
}
static class ThreadPoolTest implements Runnable{
@Override
public void run() {
try {
String dateString = fastDateFormat.format(new Date());
Date parseDate = fastDateFormat.parse(dateString);
String dateString2 = fastDateFormat.format(parseDate);
System.out.println(Thread.currentThread().getName()+" 线程是否安全: "+dateString.equals(dateString2));
} catch (Exception e) {
e.printStackTrace();
System.out.println(Thread.currentThread().getName()+" 格式化失败 ");
}
}
}
}
使用FastDateFormat能保证线程安全,且效率也是挺高的。适合高并发场景使用。
FastDateFormat源码分析
Apache Commons Lang 3.5
//FastDateFormat
@Override
public String format(final Date date) {
return printer.format(date);
} @Override
public String format(final Date date) {
final Calendar c = Calendar.getInstance(timeZone, locale);
c.setTime(date);
return applyRulesToString(c);
}
源码中 Calender 是在 format 方法里创建的,肯定不会出现 setTime 的线程安全问题。这样线程安全疑惑解决了。那还有性能问题要考虑?
我们来看下FastDateFormat是怎么获取的
FastDateFormat.getInstance();
FastDateFormat.getInstance(CHINESE_DATE_TIME_PATTERN);
看下对应的源码
/**
* 获得 FastDateFormat实例,使用默认格式和地区
*
* @return FastDateFormat
*/
public static FastDateFormat getInstance() {
return CACHE.getInstance();
} /**
* 获得 FastDateFormat 实例,使用默认地区<br>
* 支持缓存
*
* @param pattern 使用{@link java.text.SimpleDateFormat} 相同的日期格式
* @return FastDateFormat
* @throws IllegalArgumentException 日期格式问题
*/
public static FastDateFormat getInstance(final String pattern) {
return CACHE.getInstance(pattern, null, null);
}
这里有用到一个CACHE,看来用了缓存,往下看
private static final FormatCache<FastDateFormat> CACHE = new FormatCache<FastDateFormat>(){
@Override
protected FastDateFormat createInstance(final String pattern, final TimeZone timeZone, final Locale locale) {
return new FastDateFormat(pattern, timeZone, locale);
}
};
//
abstract class FormatCache<F extends Format> {
...
private final ConcurrentMap<Tuple, F> cInstanceCache = new ConcurrentHashMap<>(7);
private static final ConcurrentMap<Tuple, String> C_DATE_TIME_INSTANCE_CACHE = new ConcurrentHashMap<>(7);
...
}

在getInstance 方法中加了ConcurrentMap 做缓存,提高了性能。且我们知道ConcurrentMap 也是线程安全的。
实践
/**
* 年月格式 {@link FastDateFormat}:yyyy-MM
*/
public static final FastDateFormat NORM_MONTH_FORMAT = FastDateFormat.getInstance(NORM_MONTH_PATTERN);

//FastDateFormat
public static FastDateFormat getInstance(final String pattern) {
return CACHE.getInstance(pattern, null, null);
}


如图可证,是使用了ConcurrentMap 做缓存。且key值是格式,时区和locale(语境)三者都相同为相同的key。
结论
1、不要定义为static变量,使用局部变量
2、加锁:synchronized锁和Lock锁
3、使用ThreadLocal方式
4、使用DateTimeFormatter代替SimpleDateFormat(DateTimeFormatter是线程安全的,java 8+支持)
5、使用FastDateFormat 替换SimpleDateFormat(FastDateFormat 是线程安全的,Apache Commons Lang包支持,java8之前推荐此用法)
SimpleDateFormat线程不安全了?这里有5种解决方案的更多相关文章
- iOS多线程全套:线程生命周期,多线程的四种解决方案,线程安全问题,GCD的使用,NSOperation的使用
目的 本文主要是分享iOS多线程的相关内容,为了更系统的讲解,将分为以下7个方面来展开描述. 多线程的基本概念 线程的状态与生命周期 多线程的四种解决方案:pthread,NSThread,GCD,N ...
- SimpleDateFormat线程不安全及解决办法
原文链接:https://blog.csdn.net/csdn_ds/article/details/72984646 以前没有注意到SimpleDateFormat线程不安全的问题,写时间工具类,一 ...
- SimpleDateFormat线程不安全及解决办法(转)
以前没有注意到SimpleDateFormat线程不安全的问题,写时间工具类,一般写成静态的成员变量,不知,此种写法的危险性!在此讨论一下SimpleDateFormat线程不安全问题,以及解决方法. ...
- SimpleDateFormat线程不安全原因及解决方案
一. 线程不安全验证: /** * SimpleDateFormat线程安全测试 * 〈功能详细描述〉 * * @author 17090889 * @see [相关类/方法](可选) * @sinc ...
- SimpleDateFormat线程不安全的5种解决方案!
1.什么是线程不安全? 线程不安全也叫非线程安全,是指多线程执行中,程序的执行结果和预期的结果不符的情况就叫做线程不安全. 线程不安全的代码 SimpleDateFormat 就是一个典型的线程不 ...
- Atitit usrqbg1821 Tls 线程本地存储(ThreadLocal Storage 规范标准化草案解决方案ThreadStatic
Atitit usrqbg1821 Tls 线程本地存储(ThreadLocal Storage 规范标准化草案解决方案ThreadStatic 1.1. ThreadLocal 设计模式1 1.2. ...
- 【Java_多线程并发编程】基础篇—线程状态及实现多线程的两种方式
1.Java多线程的概念 同一时间段内,位于同一处理器上多个已开启但未执行完毕的线程叫做多线程.他们通过轮寻获得CPU处理时间,从而在宏观上构成一种同时在执行的假象,实质上在任意时刻只有一个线程获得C ...
- JAVA - 线程从创建到死亡的几种状态都有哪些?
JAVA - 线程从创建到死亡的几种状态都有哪些? 新建( new ):新创建了一个线程对象. 可运行( runnable ):线程对象创建后,其他线程(比如 main 线程)调用了该对象 的 sta ...
- SimpleDateFormat线程不安全问题处理
在工作中,通过SimpleDateFormat将字符串类型转为日期类型时,发现有时返回的日期类型出错,调用方法如下: public final class DateUtil { static fina ...
- SimpleDateFormat 线程不安全及解决方案
SimpleDateFormat定义 SimpleDateFormat 是一个以与语言环境有关的方式来格式化和解析日期的具体类.它允许进行格式化(日期 -> 文本).解析(文本 -> 日期 ...
随机推荐
- 服务器常见问题排查(一)——cpu占用高、上下文频繁切换、频繁GC
一般而言cpu异常往往还是比较好定位的.原因包括业务逻辑问题(死循环).频繁gc以及上下文切换过多.而最常见的往往是业务逻辑(或者框架逻辑)导致的,可以使用jstack来分析对应的堆栈情况. 使用js ...
- Python 利用pandas 和 matplotlib绘制柱状图
当你需要展示数据时,图表是一个非常有用的工具.Python 中的 pandas 和 matplotlib 库提供了丰富的功能,可以帮助你轻松地绘制各种类型的图表.本文将介绍如何使用这两个库,绘制一个店 ...
- 数据库系列:MySQL引擎MyISAM和InnoDB的比较
1.数据库核心知识点 数据库系列:MySQL慢查询分析和性能优化 数据库系列:MySQL索引优化总结(综合版) 数据库系列:高并发下的数据字段变更 数据库系列:覆盖索引和规避回表 数据库系列:数据库高 ...
- 一些 trick 和思考收获
2023.1.7 P1117 优秀的拆分 对于一眼看上去只能直接求解的题可以设置一些节点变为求每个节点的贡献 *2023 7.24 补充:这个 trick 也被称为设置关键点,通常用于区间长度固定或是 ...
- 从零实现的浏览器Web脚本
从零实现的浏览器Web脚本 在之前我们介绍了从零实现Chrome扩展,而实际上浏览器级别的扩展整体架构非常复杂,尽管当前有统一规范但不同浏览器的具体实现不尽相同,并且成为开发者并上架Chrome应用商 ...
- ChatGLM3-6B:新一代开源双语对话语言模型,流畅对话与低部署门槛再升级
ChatGLM3-6B:新一代开源双语对话语言模型,流畅对话与低部署门槛再升级 1.ChatGLM3简介 ChatGLM3 是智谱AI和清华大学 KEG 实验室联合发布的新一代对话预训练模型.Chat ...
- python中pip下载慢或报错的解决方法
一:问题 python的pip在安装包时,有时会报错超时,排除包名写错的原因,一般这种问题是因为网络下载过慢,导致超时 二:解决方案 我们可以设置pip镜像源下载,能够提升pip下载速度,解决报错问题 ...
- JavaWeb项目中web.xml配置文件<servlet-class>…</servlet-class>中的路径出现问题以及服务器错误的解决办法
问题如图 原因: 1.改变了 WEB-INF 文件夹下 lib 文件夹下 servlet-api.jar 的路径2.缺失lib文件夹下的 servlet-api.jar,没有添加到库中 解决办法: 不 ...
- 热烈祝贺:薪火数据(https://www.datainside.com.cn 数据中心低代码搭建平台)参加教育博览会取得圆满成功。
- SQL执行insert into后返回主键ID
1 select @@identity 2 select SCOPE_IDENTITY() 3 select IDENT_CURRENT('table') 注解:@@IDENTITY 返回当前会话的所 ...