使用ThreadLocal进行日期转换
我要求将传入日期字符串格式“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));
Java中的ThreadLocal除了编写不可变类之外,还是一种实现线程安全的方法。 由于SimpleDateFormat不是线程安全的,因此您可以使用ThreadLocal使其线程安全。
class DateFormatter{ private static ThreadLocal outDateFormatHolder = new ThreadLocal () { @Override protected SimpleDateFormat initialValue() { return new SimpleDateFormat("MM/dd/yyyy"); } }; private static ThreadLocal inDateFormatHolder = new ThreadLocal () { @Override protected SimpleDateFormat initialValue() { return new SimpleDateFormat("yyyyMMdd"); } }; public static String formatDate(String date) throws ParseException { return outDateFormatHolder.get().format( inDateFormatHolder.get().parse(date)); } }
这背后的想法是SimpleDateFormat不是线程安全的,因此在multithreading应用程序中,您无法在多个线程之间共享SimpleDateFormat的实例。 但是由于SimpleDateFormat的创建是一项昂贵的操作,我们可以使用ThreadLocal作为解决方法
static ThreadLocal format1 = new ThreadLocal () { @Override protected SimpleDateFormat initialValue() { return new SimpleDateFormat("yyyy-MM-dd"); } }; public String formatDate(Date date) { return format1.get().format(date); }