新的SimpleDateFormat始终为给定的dateFormat返回相同的引用 [英] new SimpleDateFormat always returns same reference for a given dateFormat
问题描述
我试图通过在多个线程中使用相同的SimpleDateFormat实例来复制错误.但是,我陷入了另一个问题,没有找到任何答案.
I was trying to replicate a bug by using the same instance of SimpleDateFormat across multiple threads. However I got stuck with another problem and did not find any answers to it.
这个简单的代码块复制了我所看到的问题.
This simple code block replicates the issues I am seeing.
DateFormat d1 = new SimpleDateFormat("ddMMyyyy");
DateFormat d2 = new SimpleDateFormat("ddMMyyyy");
DateFormat d3 = new SimpleDateFormat("ddMMyy");
System.out.println("d1 = " + d1);
System.out.println("d2 = " + d2);
System.out.println("d3 = " + d3);
在Java 7(1.7_0_21)下执行此操作的结果如下
The results of this operations under java 7 (1.7_0_21) is as follows
d1 = java.text.SimpleDateFormat@c5bfbc60
d2 = java.text.SimpleDateFormat@c5bfbc60
d3 = java.text.SimpleDateFormat@b049fd40
您可以看到,尽管我正在为d1和d2创建新对象,但它们最终都是相同的引用.d3由于模式不同而最终成为一个新实例.
As you can see that although I am creating new objects for d1 and d2 they end up being the same reference. d3 ends up being a new instance as pattern is different.
java编译/运行时是否进行此优化?任何指针都会有所帮助
Does java compile/runtime do this optimization? Any pointers will be helpful
推荐答案
SimpleDateFormat
或 DateFormat
( SimpleDateFormat
超类)或 Format
( toString()
,因此 Object
toString()>类实际上已执行,其代码为:
SimpleDateFormat
nor DateFormat
(SimpleDateFormat
superclass) nor Format
(DateFormat
superclass) have a toString()
implemented, so the toString()
from the Object
class is actually executed, whose code is :
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
现在,生成 SimpleDateFormat
hashCode:
Now, SimpleDateFormat
hashCode is generated:
public int hashCode()
{
return pattern.hashCode();
// just enough fields for a reasonable distribution
}
这意味着,如果您创建多个具有相同 pattern
的 SimpleDateFormat
实例,就像您的情况一样,它们将具有相同的 hashCode
,因此 toString()
对于这些实例将返回相同的结果.
Which means that if you create numerous SimpleDateFormat
instances with the same pattern
, like in your case, they will have the same hashCode
and hence toString()
will return the same for these instances.
此外,正如rixmath发现的那样,具有相同 pattern
的 SimpleDateFormat
实例也将相等.
Moreover, as it has been spotted by rixmath, SimpleDateFormat
instances with the same pattern
will also be equal.
这篇关于新的SimpleDateFormat始终为给定的dateFormat返回相同的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!