使用ThreadLocal进行日期转换

use*_*017 8 java date-conversion simpledateformat

我要求将传入日期字符串格式"20130212"(YYYYMMDD)转换为12/02/2013(DD/MM/YYYY)

使用ThreadLocal.我知道一种方法可以做到这一点,没有ThreadLocal.谁能帮我?

转换没有ThreadLocal:

    final SimpleDateFormat format2 = new SimpleDateFormat("MM/dd/yyyy");
    final SimpleDateFormat format1 = new SimpleDateFormat("yyyyMMdd");
    final Date date = format1.parse(tradeDate);
    final Date formattedDate = format2.parse(format2.format(date));
Run Code Online (Sandbox Code Playgroud)

Evg*_*eev 12

这背后的想法是SimpleDateFormat不是线程安全的,因此在多线程应用程序中,您无法在多个线程之间共享SimpleDateFormat的实例.但是由于SimpleDateFormat的创建是一项昂贵的操作,我们可以使用ThreadLocal作为解决方法

static ThreadLocal<SimpleDateFormat> format1 = new ThreadLocal<SimpleDateFormat>() {
    @Override
    protected SimpleDateFormat initialValue() {
        return new SimpleDateFormat("yyyy-MM-dd");
    }
};

public String formatDate(Date date) {
    return format1.get().format(date);
}
Run Code Online (Sandbox Code Playgroud)


Ric*_*hie 11

Java中的ThreadLocal除了编写不可变类之外,还是一种实现线程安全的方法.由于SimpleDateFormat不是线程安全的,因此您可以使用ThreadLocal使其线程安全.

class DateFormatter{

    private static ThreadLocal<SimpleDateFormat> outDateFormatHolder = new ThreadLocal<SimpleDateFormat>() {
    @Override
    protected SimpleDateFormat initialValue() {
        return new SimpleDateFormat("MM/dd/yyyy");
    }
};

private static ThreadLocal<SimpleDateFormat> inDateFormatHolder = new ThreadLocal<SimpleDateFormat>() {
    @Override
    protected SimpleDateFormat initialValue() {
        return new SimpleDateFormat("yyyyMMdd");
    }
};

public static String formatDate(String date) throws ParseException { 
    return outDateFormatHolder.get().format(
            inDateFormatHolder.get().parse(date));
}        
}
Run Code Online (Sandbox Code Playgroud)