SimpleDateFormat的javadoc指出SimpleDateFormat不同步。同步对SimpleDateFormat的访问
“的日期格式不同步。这 建议为每个线程创建独立的 格式实例。如果 多个线程同时访问一个格式 同时,它必须保持外部同步 。”
但在多线程环境中使用SimpleDateFormat实例的最佳方法是什么?以下是我想到的一些选项,过去我使用过选项1和2,但我很想知道是否有更好的选择,或者哪些选项可以提供最佳性能和并发性。
选项1:需要
public String formatDate(Date d) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return sdf.format(d);
}
选项2时创建本地实例:创建SimpleDateFormat的实例为类变量而是将其同步访问。
private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
public String formatDate(Date d) {
synchronized(sdf) {
return sdf.format(d);
}
}
方案3:创建一个ThreadLocal存储的SimpleDateFormat的不同实例,为每个线程。
private ThreadLocal<SimpleDateFormat> tl = new ThreadLocal<SimpleDateFormat>();
public String formatDate(Date d) {
SimpleDateFormat sdf = tl.get();
if(sdf == null) {
sdf = new SimpleDateFormat("yyyy-MM-hh");
tl.set(sdf);
}
return sdf.format(d);
}
+1提出这个问题。许多人认为SimpleDateFormat是线程安全的(我在各处都能看到假设)。 – 2011-03-03 18:50:39
有关ThreadLocal方法的详细信息,请参阅: http://www.javaspecialists.eu/archive/Issue172.html – miner49r 2012-02-04 14:02:11
为什么请参阅此问题:http://stackoverflow.com/questions/6840803/simpledateformat-线程安全 – Raedwald 2013-06-13 12:17:46