SimpleDateFormate线程安全

一、线程安全问题产生的原因

线程安全问题都是由全局变量及静态变量引起的

二、线程安全问题

SimpleDateFormate sdf = new SimpleDateFormat();使用sdf.parse(dateStr);sdf.format(date);在sdf内有一个对Caleadar对象的引用,在源码sdf.parse(dateStr);源码中calendar.clear();和calendar.getTime(); // 获取calendar的时间

如果 线程A 调用了 sdf.parse(), 并且进行了 calendar.clear()后还未执行calendar.getTime()的时候,线程B又调用了sdf.parse(), 这时候线程B也执行了sdf.clear()方法, 这样就导致线程A的的calendar数据被清空了;

ThreadLocal是使用空间换时间,synchronized是使用时间换空间

使用ThreadLocal解决线程安全:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class ThreadLocalDateUtil {
     private static final String date_format = "yyyy-MM-dd HH:mm:ss" ;
     private static ThreadLocal<DateFormat> threadLocal = new ThreadLocal<DateFormat>();
  
     public static DateFormat getDateFormat()  
    
         DateFormat df = threadLocal.get(); 
         if (df== null ){ 
             df = new SimpleDateFormat(date_format); 
             threadLocal.set(df); 
        
         return df; 
    
     public static String formatDate(Date date) throws ParseException {
         return getDateFormat().format(date);
     }
     public static Date parse(String strDate) throws ParseException {
         return getDateFormat().parse(strDate);
     }  
}

使用synchronized解决方案:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class DateSyncUtil {
     private static SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
       
     public static String formatDate(Date date) throws ParseException{
         synchronized (sdf){
             return sdf.format(date);
        
     }
     
     public static Date parse(String strDate) throws ParseException{
         synchronized (sdf){
             return sdf.parse(strDate);
         }
     }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值