Java知识

高并发情景下避免使用SimpleDateFormat

2018-05-29  本文已影响521人  寇寇寇先森

平时写程序都习惯了使用SimpleDateFormat,当需要创建当前时间的时间戳,直接调用老套方法

SimpleDateFormat df= new SimpleDateFormat("yyyy-MM-dd");

然后需要创建时间戳的时候,直接调用方法

df.format (new Date()) 

在单线程工程中,这种方法毫无问题,但是如果在多线程高并发情景中,这种问题就可能会发生问题。因为SimpleDateFormat是线程不安全的,多线程环境下不能用。不然,可能会发生一些跟你预期不一样的结果。
如何解决?
使用ThreadLocal,我自定义了一个线程安全工具类,代码如下:

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);
    }   
}

//使用完ThreadLocal记得安全清楚,避免内存泄漏
public static void safeClear() {
        threadLocal.remove();
    }

这样,以后创建时间戳和转换解析时间戳都用ThreadLocalDateUtil 的方法,能保证线程安全。

上一篇下一篇

猜你喜欢

热点阅读