SimpleDateFormat线程不安全及解决的方法
一. 为什么SimpleDateFormat不是线程安全的?
Java源代码例如以下:
/**
* Date formats are not synchronized.
* It is recommended to create separate format instances for each thread.
* If multiple threads access a format concurrently, it must be synchronized
* externally.
*/
public class SimpleDateFormat extends DateFormat { public Date parse(String text, ParsePosition pos){
calendar.clear(); // Clears all the time fields
// other logic ...
Date parsedDate = calendar.getTime();
}
} abstract class DateFormat{
// other logic ...
protected Calendar calendar;
public Date parse(String source) throws ParseException{
ParsePosition pos = new ParsePosition(0);
Date result = parse(source, pos);
if (pos.index == 0)
throw new ParseException("Unparseable date: \"" + source + "\"" ,
pos.errorIndex);
return result;
}
}
假设我们把SimpleDateFormat定义成static成员变量,那么多个thread之间会共享这个sdf对象, 所以Calendar对象也会共享。
假定线程A和线程B都进入了parse(text, pos) 方法。 线程B运行到calendar.clear()后,线程A运行到calendar.getTime(), 那么就会有问题。
二. 问题重现:
public class DateFormatTest {
private static SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);
private static String date[] = { "01-Jan-1999", "01-Jan-2000", "01-Jan-2001" }; public static void main(String[] args) {
for (int i = 0; i < date.length; i++) {
final int temp = i;
new Thread(new Runnable() {
@Override
public void run() {
try {
while (true) {
String str1 = date[temp];
String str2 = sdf.format(sdf.parse(str1));
System.out.println(Thread.currentThread().getName() + ", " + str1 + "," + str2);
if(!str1.equals(str2)){
throw new RuntimeException(Thread.currentThread().getName()
+ ", Expected " + str1 + " but got " + str2);
}
}
} catch (Exception e) {
throw new RuntimeException("parse failed", e);
}
}
}).start();
}
}
}
创建三个进程, 使用静态成员变量SimpleDateFormat的parse和format方法。然后比較经过这两个方法折腾后的值是否相等:
程序假设出现下面错误,说明传入的日期就串掉了,即SimpleDateFormat不是线程安全的:
Exception in thread "Thread-0" java.lang.RuntimeException: parse failed
at cn.test.DateFormatTest$1.run(DateFormatTest.java:27)
at java.lang.Thread.run(Thread.java:662)
Caused by: java.lang.RuntimeException: Thread-0, Expected 01-Jan-1999 but got 01-Jan-2000
at cn.test.DateFormatTest$1.run(DateFormatTest.java:22)
... 1 more
三. 解决方式:
1. 解决方式a:
将SimpleDateFormat定义成局部变量:
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);
String str1 = "01-Jan-2010";
String str2 = sdf.format(sdf.parse(str1));
缺点:每调用一次方法就会创建一个SimpleDateFormat对象,方法结束又要作为垃圾回收。
2. 解决方式b:
加一把线程同步锁:synchronized(lock)
public class SyncDateFormatTest {
private static SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);
private static String date[] = { "01-Jan-1999", "01-Jan-2000", "01-Jan-2001" }; public static void main(String[] args) {
for (int i = 0; i < date.length; i++) {
final int temp = i;
new Thread(new Runnable() {
@Override
public void run() {
try {
while (true) {
synchronized (sdf) {
String str1 = date[temp];
Date date = sdf.parse(str1);
String str2 = sdf.format(date);
System.out.println(Thread.currentThread().getName() + ", " + str1 + "," + str2);
if(!str1.equals(str2)){
throw new RuntimeException(Thread.currentThread().getName()
+ ", Expected " + str1 + " but got " + str2);
}
}
}
} catch (Exception e) {
throw new RuntimeException("parse failed", e);
}
}
}).start();
}
}
}
缺点:性能较差,每次都要等待锁释放后其它线程才干进入
3. 解决方式c: (推荐)
使用ThreadLocal: 每一个线程都将拥有自己的SimpleDateFormat对象副本。
写一个工具类:
public class DateUtil {
private static ThreadLocal<SimpleDateFormat> local = new ThreadLocal<SimpleDateFormat>(); public static Date parse(String str) throws Exception {
SimpleDateFormat sdf = local.get();
if (sdf == null) {
sdf = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);
local.set(sdf);
}
return sdf.parse(str);
} public static String format(Date date) throws Exception {
SimpleDateFormat sdf = local.get();
if (sdf == null) {
sdf = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);
local.set(sdf);
}
return sdf.format(date);
}
}
測试代码:
public class ThreadLocalDateFormatTest {
private static String date[] = { "01-Jan-1999", "01-Jan-2000", "01-Jan-2001" }; public static void main(String[] args) {
for (int i = 0; i < date.length; i++) {
final int temp = i;
new Thread(new Runnable() {
@Override
public void run() {
try {
while (true) {
String str1 = date[temp];
Date date = DateUtil.parse(str1);
String str2 = DateUtil.format(date);
System.out.println(str1 + "," + str2);
if(!str1.equals(str2)){
throw new RuntimeException(Thread.currentThread().getName()
+ ", Expected " + str1 + " but got " + str2);
}
}
} catch (Exception e) {
throw new RuntimeException("parse failed", e);
}
}
}).start();
}
}
}
SimpleDateFormat线程不安全及解决的方法的更多相关文章
- SimpleDateFormat线程不安全及解决办法
原文链接:https://blog.csdn.net/csdn_ds/article/details/72984646 以前没有注意到SimpleDateFormat线程不安全的问题,写时间工具类,一 ...
- SimpleDateFormat线程不安全及解决办法(转)
以前没有注意到SimpleDateFormat线程不安全的问题,写时间工具类,一般写成静态的成员变量,不知,此种写法的危险性!在此讨论一下SimpleDateFormat线程不安全问题,以及解决方法. ...
- SimpleDateFormat线程不安全问题解决及替换方法
场景:在多线程情况下为避免多次创建SimpleDateForma实力占用资源,将SimpleDateForma对象设置为static. 出现错误:SimpleDateFormat定义为静态变量,那么多 ...
- SimpleDateFormat线程不安全的5种解决方案!
1.什么是线程不安全? 线程不安全也叫非线程安全,是指多线程执行中,程序的执行结果和预期的结果不符的情况就叫做线程不安全. 线程不安全的代码 SimpleDateFormat 就是一个典型的线程不 ...
- Java多线程初学者指南(8):从线程返回数据的两种方法
从线程中返回数据和向线程传递数据类似.也可以通过类成员以及回调函数来返回数据.但类成员在返回数据和传递数据时有一些区别,下面让我们来看看它们区别在哪. 一.通过类变量和方法返回数据 使用这种方法返回数 ...
- Android中UI线程与后台线程交互设计的5种方法
我想关于这个话题已经有很多前辈讨论过了.今天算是一次学习总结吧. 在android的设计思想中,为了确保用户顺滑的操作体验.一 些耗时的任务不能够在UI线程中运行,像访问网络就属于这类任务.因此我们必 ...
- .NET一个线程更新另一个线程的UI(两种实现方法及若干简化)
Winform中的控件是绑定到特定的线程的(一般是主线程),这意味着从另一个线程更新主线程的控件不能直接调用该控件的成员. 控件绑定到特定的线程这个概念如下: 为了从另一个线程更新主线程的Window ...
- 线程的状态有哪些,线程中的start与run方法的区别
线程在一定条件下,状态会发生变化.线程一共有以下几种状态: 1.新建状态(New):新创建了一个线程对象. 2.就绪状态(Runnable):线程对象创建后,其他线程调用了该对象的start()方法. ...
- Android Eclipseproject开发中的常见调试问题(二)android.os.NetworkOnMainThreadException 异常的解决的方法
android.os.NetworkOnMainThreadException 异常的解决的方法. 刚开是把HttpURLConnectionnection 打开连接这种方法放在UI线程里了,可能不是 ...
随机推荐
- Android ListView工作原理完全解析,带你从源码的角度彻底理解
版权声明:本文出自郭霖的博客,转载必须注明出处. 目录(?)[+] Adapter的作用 RecycleBin机制 第一次Layout 第二次Layout 滑动加载更多数据 转载请注明出处:h ...
- OpenCV学习(4) Mat的基本操作(1)
图像在OpenCV中都是通过Mat类来存储的,Mat可以用来表示N维矩阵,当然用的最多的还是二维矩阵. Mat类有两部分组成:第一部分是头信息,这些信息主要用来描述矩阵,比如矩 ...
- POJ 2046 Gap 搜索- 状态压缩
题目地址: http://poj.org/problem?id=2046 一道搜索状态压缩的题目,关键是怎样hash. AC代码: #include <iostream> #include ...
- 使用Proxmark3进行MIFARE Classic卡的安全测试
使用Proxmark3进行MIFARE Classic卡的安全测试 Proxmark3的MIFARE安全测试是很多朋友都非常重视的一部分,所以我们特地以这个部分进行介绍,告诉大家如何当你完成前期操 ...
- osglightpoint例子 [转]
该例子演示了光点的效果,主要应用osgSim库中的LightPoint.LightPointNode. SequenceGroup.BlinkSequence,osgSim库属于仿真库,扩展库.应用o ...
- jquery获取第一层li
<ul id="aaa"> <li>aaa</li> <li>aaa <ul> <li>bbb</li ...
- 【cocos2d-x 3.7 飞机大战】 决战南海I (七) 控制器的实现
控制器中的功能并不多,主要是以下这些 //对玩家分数的操作 CC_SYNTHESIZE_READONLY(SaveData *, m_saveData, SaveData); void update( ...
- reportservice报表单元格依据条件显示不同的颜色
有时候.我们须要依据条件,让单元格显示不同的颜色: watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQveV9mMTIz/font/5a6L5L2T/fontsi ...
- 使用IntelliJ IDEA开发Spring MVC HelloWorld
https://blog.csdn.net/industriously/article/details/52851588 https://blog.csdn.net/slow_wakler/artic ...
- 使用Nodejs的Nodemailer通过163信箱发送邮件例程
首先需要安装一下nodemailer #nmp nodemailer install --save 然后就参照官方文档的例程改写一下就行了,代码如下: 'use strict'; const node ...