SimpleDateFormat 线程不安全及解决方案
SimpleDateFormat定义
SimpleDateFormat 是一个以与语言环境有关的方式来格式化和解析日期的具体类。它允许进行格式化(日期 -> 文本)、解析(文本 -> 日期)和规范化。 SimpleDateFormat 使得可以选择任何用户定义的日期-时间格式的模式。但是,仍然建议通过 DateFormat 中的 getTimeInstance、getDateInstance 或 getDateTimeInstance
来创建日期-时间格式器。每一个这样的类方法都能够返回一个以默认格式模式初始化的日期/时间格式器。可以根据需要使用 applyPattern 方法来修改格式模式。
官网同步建议
同步
日期格式是不同步的。建议为每个线程创建独立的格式实例。如果多个线程同时访问一个格式,则它必须是外部同步的。
为什么线程不安全

上图中,SimpleDateFormat类中,有个对象calendar
calendar
DateFormat 使用 calendar 来生成实现日期和时间格式化所需的时间字段值。
当SimpleDateFormat用static申明,多个线程共享SimpleDateFormat对象是,也共享该对象的calendar对象。而当调用parse方法时,会clear所有日历字段和值。当线程A正在调用parse,线程B调用clear,这样解析后的数据就会出现偏差
//parse方法
@Override
public Date parse(String text, ParsePosition pos)
{
try {
parsedDate = calb.establish(calendar).getTime();
...
}
}
//establish方法
Calendar establish(Calendar cal) {
...
//将此 Calendar 的所有日历字段值和时间值(从历元至现在的毫秒偏移量)设置成未定义
cal.clear();
}
同样 formart中也用到了calendar对象,将date设置到日历的时间字段中
private StringBuffer format(Date date, StringBuffer toAppendTo,
FieldDelegate delegate) {
// Convert input date to time field list
calendar.setTime(date);
...
}
当线程A调用setTime,而线程B也调用setTime,这时候线程A最后得到的时间是 最后线程B的时间。也会导致数据偏差
不安全示例:
public static void main(String[] args) throws InterruptedException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateStr = "1111-11-11 11:11:11";
ExecutorService executorService = Executors.newFixedThreadPool();
for(int i=;i<;i++) {
executorService.submit(new Runnable() {
@Override
public void run() {
try {
//多个线程操作同一个sdf对象
System.out.println(sdf.format(sdf.parse(dateStr)) + "---" + Thread.currentThread().getName());
} catch (ParseException e) {
System.out.println("--------------> error, " + e.getMessage());
}
}
});
}
executorService.shutdown();
}
执行结果:
...
-- ::---pool--thread-
0011-- ::---pool--thread-
0011-- ::---pool--thread-
-- ::---pool--thread-
-- ::---pool--thread-
-- ::---pool--thread-
-- ::---pool--thread-
-- 00::---pool--thread-
-- ::---pool--thread-
...
可以看到数据出现偏差
解决方案
1.为每个实例创建一个单独的SimpleDateFormat对象
public static void main(String[] args) throws InterruptedException {
//SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateStr = "1111-11-11 11:11:11";
ExecutorService executorService = Executors.newFixedThreadPool();
for(int i=;i<;i++) {
executorService.submit(new Runnable() {
//为每个线程创建自己的sdf对象
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@Override
public void run() {
try {
System.out.println(sdf.format(sdf.parse(dateStr)) + "---" + Thread.currentThread().getName());
} catch (ParseException e) {
System.out.println("--------------> error, " + e.getMessage());
}
}
});
}
executorService.shutdown();
}
缺点:每次new一个实例,都会new一个format对象,虚拟机内存消耗大,垃圾回收频繁
2.给静态SimpleDateFormat对象加锁,使用Lock或者synchronized修饰
public static void main(String[] args) throws InterruptedException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateStr = "1111-11-11 11:11:11";
ExecutorService executorService = Executors.newFixedThreadPool();
for(int i=;i<;i++) {
executorService.submit(new Runnable() {
@Override
public void run() {
//加同步锁
synchronized (sdf) {
try {
System.out.println(sdf.format(sdf.parse(dateStr)) + "---" + Thread.currentThread().getName());
} catch (ParseException e) {
System.out.println("--------------> error, " + e.getMessage());
}
}
}
});
}
executorService.shutdown();
}
缺点:性能差,其他线程要等待锁释放
3.使用ThreadLocal为每个线程创建一个SimpleDateFormat对象副本,有线程隔离性,各自的副本对象也不会被其他线程影响
public static void main(String[] args) throws InterruptedException {
//SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//初始化threadLocal并设置值
ThreadLocal<SimpleDateFormat> threadLocal = new ThreadLocal<SimpleDateFormat>(){
@Override
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
}
};
String dateStr = "1111-11-11 11:11:11";
ExecutorService executorService = Executors.newFixedThreadPool(100);
for(int i=0;i<100;i++) {
executorService.submit(new Runnable() {
@Override
public void run() {
try {
System.out.println(threadLocal.get().format(threadLocal.get().parse(dateStr)) + "---" + Thread.currentThread().getName());
} catch (ParseException e) {
System.out.println("--------------> error, " + e.getMessage());
}
}
});
}
executorService.shutdown();
//清理threadLocal,生产环境不清理容易导致内存溢出
threadLocal.remove();
}
ThreadLocal原理分析
SimpleDateFormat 线程不安全及解决方案的更多相关文章
- SimpleDateFormat线程不安全的5种解决方案!
1.什么是线程不安全? 线程不安全也叫非线程安全,是指多线程执行中,程序的执行结果和预期的结果不符的情况就叫做线程不安全. 线程不安全的代码 SimpleDateFormat 就是一个典型的线程不 ...
- SimpleDateFormat线程不安全原因及解决方案
一. 线程不安全验证: /** * SimpleDateFormat线程安全测试 * 〈功能详细描述〉 * * @author 17090889 * @see [相关类/方法](可选) * @sinc ...
- SimpleDateFormat线程不安全及解决办法
原文链接:https://blog.csdn.net/csdn_ds/article/details/72984646 以前没有注意到SimpleDateFormat线程不安全的问题,写时间工具类,一 ...
- SimpleDateFormat线程不安全及解决办法(转)
以前没有注意到SimpleDateFormat线程不安全的问题,写时间工具类,一般写成静态的成员变量,不知,此种写法的危险性!在此讨论一下SimpleDateFormat线程不安全问题,以及解决方法. ...
- SimpleDateFormat 线程安全的解决方案--DateTimeFormatter
SimpleDateFormat并不是线程安全的,因为在SimpleDateFormat中持有一个Calendar类对象在Parse 和Format方法时会调用calendar.setTime(dat ...
- SimpleDateFormat线程不安全问题解决及替换方法
场景:在多线程情况下为避免多次创建SimpleDateForma实力占用资源,将SimpleDateForma对象设置为static. 出现错误:SimpleDateFormat定义为静态变量,那么多 ...
- SimpleDateFormat线程安全问题排查
一. 问题现象 运营部门反馈使用小程序配置的拉新现金红包活动二维码,在扫码后跳转至404页面. 二. 原因排查 首先,检查扫码后的跳转链接地址不是对应二维码的实际URL,根据代码逻辑推测,可能是acc ...
- SimpleDateFormat线程不安全问题处理
在工作中,通过SimpleDateFormat将字符串类型转为日期类型时,发现有时返回的日期类型出错,调用方法如下: public final class DateUtil { static fina ...
- SimpleDateFormat线程不安全及解决的方法
一. 为什么SimpleDateFormat不是线程安全的? Java源代码例如以下: /** * Date formats are not synchronized. * It is recomme ...
随机推荐
- 【转】C# 定时器事件(设置时间间隔,间歇性执行某一函数,控制台程序)
using System.Timers;定时器事件代码 static void Main(string[] args) { Method(); #region 定时器事件 Timer aTimer = ...
- js实现搜索记录列表
<div class="sy_div28"> <div class="sy_div23"> <span>搜索历史</s ...
- Redis进阶之使用Lua脚本开发
1.在Redis中使用Lua 在Redis中执行Lua脚本有两种方法:eval和evalsha. (1)eval eval 脚本内容 key个数 key列表 参数列表 下面例子使用了key列表和参数列 ...
- 人生第一个过万 Star 的 github 项目诞生
写 Spring Boot 开源项目走入第三个年头,终于有一个开源项目要破万 Star 了,请各位读者大人批评指正. Spring Boot 文章 2016年,我开始学习 Spring Boot 的时 ...
- API简介
概述 API(Application Programming Interface),应用程序编程接口.Java API是一本程序员的 字典 ,是JDK中提供给我们使用的类的说明文档.这些类将底层的代码 ...
- UnityEditorWindow自建窗口扩展
这里主要记录UnityEditorWindow的创建,以及常用的API接口样式 1,创建UnityEditorWindow 在Unity目录中,创建一个名为Editor的文件夹(任何位置),然后创建如 ...
- gVim编辑器 操作篇
gVim是一款强大的编辑器,可以满足大部分语言的编程需要.尤其是其自带的模板定制功能对于Verilog来说非常受用.然而gVim有很多操作是不同于其他编辑器的,这让很多初学者望而却步,因此,本文将gV ...
- Manjaro折腾简单记录
0.Manjaro启动U盘的制作 推荐使用4-16G容量的U盘,避免兼容性问题(U盘太大可能会无法启动). 用rufus就可以,注意选用DD模式才能成功制作. 如果在linux环境里,先用sudo f ...
- synchronized和lock有什么区别?
一.原始构成 synchronized是关键字属于JVM层面,monitorenter(底层是通过monitor对象来完成,其实wait/notify等方法也依赖monitor对象只有在同步代码块和同 ...
- commons-httpclient 实现get和post请求
引入的jar包为: <!-- https://mvnrepository.com/artifact/commons-httpclient/commons-httpclient --> &l ...