您的位置:首页 > 编程语言

并发编程-SimpleDateFormat线程不安全及解决办法

2017-08-05 00:00 337 查看
一. 为什么SimpleDateFormat不是线程安全的?

Java源码如下:

一. 为什么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 SdfThreadTest2{
public static void main(String[] args) throws InterruptedException {
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
final String[] date = new String[]{"2017-01-01","2017-02-02","2017-03-03","2017-04-04","2017-05-05",
"2017-06-06","2017-07-07","2017-08-08","2017-09-09","2017-10-10","2017-11-11","2017-12-12"};
final ExecutorService es2 = Executors.newFixedThreadPool(12);
for(int i=0;i<12;i++){
final int j = i;
es2.execute(new Runnable(){

@Override
public void run() {
try {
System.out.println(j+ "->" + sdf.parse((date[j])));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
}

三. 解决方案:

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 SdfThreadTest2{
public static void main(String[] args) throws InterruptedException {
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
final String[] date = new String[]{"2017-01-01","2017-02-02","2017-03-03","2017-04-04","2017-05-05",
"2017-06-06","2017-07-07","2017-08-08","2017-09-09","2017-10-10","2017-11-11","2017-12-12"};
final ExecutorService es2 = Executors.newFixedThreadPool(12);
for(int i=0;i<12;i++){
final int j = i;
es2.execute(new Runnable(){

@Override
public void run() {
try {
synchronized(sdf){
System.out.println(j+ "->" + sdf.parse((date[j])));
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
}

缺点:性能较差,每次都要等待锁释放后其他线程才能进入

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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  SimpleDateFormat