Java 使用 ThreadLocal 进行日期转换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18589986/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Date Conversion with ThreadLocal
提问by user2680017
I have a requirement to convert incoming date string format "20130212" (YYYYMMDD) to 12/02/2013 (DD/MM/YYYY)
我需要将传入日期字符串格式“20130212”(YYYYMMDD)转换为 12/02/2013(DD/MM/YYYY)
using ThreadLocal
. I know a way to do this without the ThreadLocal
. Can anyone help me?
使用ThreadLocal
. 我知道一种无需ThreadLocal
. 谁能帮我?
Conversion without 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));
采纳答案by Richie
ThreadLocal in Java is a way to achieve thread-safety apart from writing immutable classes. Since SimpleDateFormat is not thread safe, you can use a ThreadLocal to make it thread safe.
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));
}
}
回答by Evgeniy Dorofeev
The idea behind this is that SimpleDateFormat is not thread-safe so in a mutil-threaded app you cannot share an instance of SimpleDateFormat between multiple threads. But since creation of SimpleDateFormat is an expensive operation we can use a ThreadLocal as workaround
这背后的想法是 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);
}