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线程里了,可能不是 ...
随机推荐
- Nginx集群
转自:http://hi.baidu.com/xingyuanju/blog/item/779a2a23b7ebb749935807f1.html http://hi.baidu.com/dianhu ...
- Jenkins自动部署到(远程)tomcat服务器
Jenkins的流程: 1.从版本控制中获取代码 ->2. 使用maven编译生成相应的包(jar,war) ->3. 部署到指定的地点. 其中2.主要是解决依赖的问题,或许你需要先mvn ...
- JS 与Flex交互:html中的js 与flex中的actionScript通信
Flex与JavaScript交互的问题,这里和大家分享一下,主要包括Flex调用JavaScript中的函数和JavaScript调用Flex中的函数两大部分内容. Flex 与JavaScript ...
- ownCloud 的六大神奇用法
ownCloud 是一个自行托管的开源文件同步和共享服务器.就像“行业老大” Dropbox.Google Drive.Box 和其他的同类服务一样,ownCloud 也可以让你访问自己的文件.日历. ...
- 对SVM的个人理解---浅显易懂
原文:http://blog.csdn.net/arthur503/article/details/19966891 之前以为SVM很强大很神秘,自己了解了之后发现原理并不难,不过,“大师的功力在于将 ...
- js 多域名跳转
<script>try {if( self.location == "http://cnblogs.com/endv" ) { top.location.href = ...
- [Algorithm] Coding Interview Question and Answer: Longest Consecutive Characters
Given a string, find the longest subsequence consisting of a single character. Example: longest(&quo ...
- vue - router 起步
官方API:https://router.vuejs.org/zh/guide/#javascript vue-cli for index.js export default new Router({ ...
- 说说PHP中的命名空间相关概念
说说PHP中的命名空间相关概念 1. PHP中的命名空间是什么? 什么是命名空间?"从广义上来说,命名空间是一种封装事物的方法.在非常多地方都能够见到这样的抽象概念. 比如.在操作系统中文件 ...
- Android Studio之多个Activity的滑动切换(二)
1.因为Android界面上的全部控件一般都位于Layout控件(比方RelativeLayout)之上,而布局控件能够设置响应touch事件,所以能够通过布局控件的setOnTouchListen来 ...