[英]Two different Class instances giving same hashCode
I'm encountering a bizarre issue on a JBoss server where two classes are producing the same hashCode()
. 我在JBoss服务器上遇到一个奇怪的问题,其中两个类正在生成相同的
hashCode()
。
Class<?> cl1 = Class.forName("fqn.Class1");
Class<?> cl2 = Class.forName("fqn.Class2");
out.println(cl1.getCanonicalName());
out.println(cl2.getCanonicalName());
out.println(cl1.hashCode());
out.println(cl2.hashCode());
out.println(System.identityHashCode(cl1));
out.println(System.identityHashCode(cl2));
out.println(cl1 == cl2);
out.println(cl1.equals(cl2));
out.println(cl1.getClassLoader().equals(cl2.getClassLoader()));
Produces: 产生:
fnq.Class1
fnq.Class2
494722
494722
494722
494722
false
false
true
I normally wouldn't care, but we're using a framework that caches setters using a key that is comprised of hashcodes from the class and a property name. 我通常不会在乎,但是我们正在使用一个框架,该框架使用由类的哈希码和属性名称组成的键来缓存设置器。 It's a bad design for caching, but it's beyond my control at the moment (OGNL 3.0.6 in the latest Struts 2.3.24, see source . A newer OGNL fixes the issue, but it won't be in Struts until 2.5, currently in beta.)
这是一个不好的设计缓存,但它是我无法控制的那一刻(OGNL 3.0.6最新的Struts 2.3.24,看到源 。一个新的OGNL修复的问题,但它不会在Struts中,直到2.5,目前在测试版中。)
What makes the issue somewhat bizarre to me is 使这个问题对我有些奇怪的是
I read that the RNG hashcode generator in Hotspot (the "0" strategy) can produce duplicates if there's racing threads, but I can't imagine classloading triggering that behavior. 我读到Hotspot中的RNG哈希码生成器(“ 0”策略)在存在竞速线程的情况下可以产生重复项,但是我无法想象类加载会触发该行为。
Does Hotspot use special hashcode handling when creating a Class
instance? 创建
Class
实例时,Hotspot是否使用特殊的哈希码处理?
java.lang.Class
does not override hashCode
, nor JVM handles it somehow specially. java.lang.Class
不会覆盖hashCode
,JVM也不会以某种方式对其进行特殊处理。 This is just the regular identity hashCode inherited from java.lang.Object
. java.lang.Object
继承的常规标识hashCode。 -XX:hashCode=0
(default in JDK 6 and JDK 7) the identity hashCode is calculated using global Park-Miller random number generator. -XX:hashCode=0
(JDK 6和JDK 7中的默认值)时,将使用全局Park-Miller随机数生成器来计算标识hashCode。 This algorithm produces unique integers with the period of 2^31-2
, so there is almost no chance that two objects have the same hashCode except for the reason below. 2^31-2
唯一整数,因此,除了以下原因之外,几乎没有机会使两个对象具有相同的hashCode。 hashCode
method. hashCode
方法时生成的。 So it does not matter when and how the classes are loaded. hashCode
is called concurrently. hashCode
则任何两个对象都可能发生此问题。 -XX:hashCode=5
(default in JDK 8). -XX:hashCode=5
(JDK 8中的默认值)。 This option uses thread-local Xorshift RNG.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.