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 线程不安全及解决方案的更多相关文章

  1. SimpleDateFormat线程不安全的5种解决方案!

    1.什么是线程不安全? 线程不安全也叫非线程安全,是指多线程执行中,程序的执行结果和预期的结果不符的情况就叫做线程不安全. ​ 线程不安全的代码 SimpleDateFormat 就是一个典型的线程不 ...

  2. SimpleDateFormat线程不安全原因及解决方案

    一. 线程不安全验证: /** * SimpleDateFormat线程安全测试 * 〈功能详细描述〉 * * @author 17090889 * @see [相关类/方法](可选) * @sinc ...

  3. SimpleDateFormat线程不安全及解决办法

    原文链接:https://blog.csdn.net/csdn_ds/article/details/72984646 以前没有注意到SimpleDateFormat线程不安全的问题,写时间工具类,一 ...

  4. SimpleDateFormat线程不安全及解决办法(转)

    以前没有注意到SimpleDateFormat线程不安全的问题,写时间工具类,一般写成静态的成员变量,不知,此种写法的危险性!在此讨论一下SimpleDateFormat线程不安全问题,以及解决方法. ...

  5. SimpleDateFormat 线程安全的解决方案--DateTimeFormatter

    SimpleDateFormat并不是线程安全的,因为在SimpleDateFormat中持有一个Calendar类对象在Parse 和Format方法时会调用calendar.setTime(dat ...

  6. SimpleDateFormat线程不安全问题解决及替换方法

    场景:在多线程情况下为避免多次创建SimpleDateForma实力占用资源,将SimpleDateForma对象设置为static. 出现错误:SimpleDateFormat定义为静态变量,那么多 ...

  7. SimpleDateFormat线程安全问题排查

    一. 问题现象 运营部门反馈使用小程序配置的拉新现金红包活动二维码,在扫码后跳转至404页面. 二. 原因排查 首先,检查扫码后的跳转链接地址不是对应二维码的实际URL,根据代码逻辑推测,可能是acc ...

  8. SimpleDateFormat线程不安全问题处理

    在工作中,通过SimpleDateFormat将字符串类型转为日期类型时,发现有时返回的日期类型出错,调用方法如下: public final class DateUtil { static fina ...

  9. SimpleDateFormat线程不安全及解决的方法

    一. 为什么SimpleDateFormat不是线程安全的? Java源代码例如以下: /** * Date formats are not synchronized. * It is recomme ...

随机推荐

  1. 【转】网页禁止后退键BackSpace的JavaScript实现(兼容IE、Chrome、Firefox、Opera)

    var forbidBackSpace = function (e) { // 获取event对象 var ev = e || window.event; // 获取事件源 var obj = ev. ...

  2. gcc/g++ 编译参数

    1, -E(大写),预处理 例子:gcc -E test.cpp -o test.i 预处理,把程序里的#开头的替换掉,比如#include,然后生成test.i 2,-P(大写),去掉预处理生成的杂 ...

  3. Linux(CentOS7)下远程拷贝文件,scp命令

    一.Linux版本 二.scp命令 scp [参数] [原路径] [目标路径] scp -P 22022 /home/file.war root@192.168.253.172:/home/test ...

  4. day22 面向对象

    面向对象 ''''1.面向过程编程   核心是"过程"二字,过程指的是解决问题的步骤,即先干什么再干什么   基于该思想编写程序就好比在编写一条流水线,是一种机械式的思维方式​   ...

  5. 有关CSS的overflow和border-radius的那些事,你的圆角被覆盖了吗?

    事件起因 最初是网友的一个提问,来自于我的知识星球社区: 说实话,不得不佩服这个网友的眼力,这么小的细节都能发现.不过这也正是 FineUI 一直前进的动力,来自社区的监督和促进. 从截图上看,貌似圆 ...

  6. day13(函数嵌套定义,global,nonlocal关键字,闭包,装饰器)

    一,复习 ''' 1.函数对象:函数名 => 存放的是函数的内存地址 1)函数名 - 找到的是函数的内存地址 2)函数名() - 调用函数 => 函数的返回值 eg:fn()() => ...

  7. VMware 安装 centos6.8

    参考文档:https://jingyan.baidu.com/article/49711c61964328fa441b7c93.html 准备工作 VMware Workstation Pro 下载地 ...

  8. Python类和对象

    目录 类与对象 其他方法 继承 经典类和新式类 派生 组合 接口.归一化设计与抽象类 继承实现的原理 子类中调用父类的方法 指名道姓 super()方法 多态与多态性 封装 单下划线开头 双下划线开头 ...

  9. springboot 与任务

    异步任务.定时任务.邮件任务 一.异步任务 在Java应用中,绝大多数情况下都是通过同步的方式来实现交互处理的:但是在 处理与第三方系统交互的时候,容易造成响应迟缓的情况,之前大部分都是使用 多线程来 ...

  10. Centos 使用yum安装MongoDB 4.0

    1.配置MongoDB的yum源 创建yum源文件: #cd /etc/yum.repos.d #vim mongodb-org-4.0.repo 添加以下内容:(我们这里使用阿里云的源) [mngo ...