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);
}
}
或者改写为:
1.使用Apache commons 里的FastDateFormat,宣称是既快又线程安全的SimpleDateFormat, 可惜它只能对日期进行format, 不能对日期串进行解析。
2.使用Joda-Time类库来处理时间相关问题

本文探讨了如何通过ThreadLocal和Apache Commons FastDateFormat优化线程安全的日期格式化。作者介绍了使用ThreadLocal存储线程本地日期格式化对象,并对比了FastDateFormat的高效特性,同时提及了使用Joda-Time库作为备选方案。
797

被折叠的 条评论
为什么被折叠?



