SimpleDateFormat 是非线程安全

在使用SimpleDateFormat的经常会有一些错误的用法,例如如下方式:
public class TestDateFormat{
private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
public void method1(){
sdf.format(new Date());
}
public void method2(){
sdf.format(new Date());
}
)
为了渐少new 的次数而把SimpleDateFormat做成成员或者静态成员,但这样的做法是隐含着错误的,是不
安全的。如下给出证明:
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


public class TestDateFormat{
private SimpleDateFormat sdf ;
public static void main(String[] args) {
SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");
Date date1 = new Date();
Date date2 = new Date(date1.getTime()+1000*60*60*24);
System.out.println(date1);
System.out.println(date2);
Thread thread1 = new Thread(new Thread1(sdf,date1));
thread1.start();
Thread thread2 = new Thread(new Thread2(sdf,date2));
thread2.start();
}

}
class Thread1 implements Runnable{
private SimpleDateFormat sdf;
private Date date;
public Thread1(SimpleDateFormat sdf,Date date){
this.sdf = sdf;
this.date = date;
}
public void run() {
for(;;){
String strDate = sdf.format(date);
if("2007-02-27".equals(strDate)){
System.err.println("Error: date1="+strDate);
System.exit(0);
}
}
}
}
class Thread2 implements Runnable{
private SimpleDateFormat sdf;
private Date date;
public Thread2(SimpleDateFormat sdf,Date date){
this.sdf = sdf;
this.date = date;
}
public void run() {
for(;;){
String strDate = sdf.format(date);
if("2007-02-26".equals(strDate)){
System.err.println("Error: date1="+strDate);
System.exit(0);
}
}
}
}
很快,基本几十次就会出现错误。错误原因:
因为SimpleDateFormat处理复杂,Jdk的实现中使用了成员变量来传递参数,这个就造成在多线程的时候
会出现错误。上边的程序证明了这个问题。

再看看SimpleDateFormat的Jdk 的Source,有这么一段注释,说明它不是线程安全的。
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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值