If Java's garbage collector moves objects, what is Object.hashCode and System.identityHashCode?

老子叫甜甜 提交于 2019-12-02 20:10:31
Chris Shain

.NET's implementation is intentionally not published (and when you attempt to decompile it, you will find that it makes an unmanaged framework call). The only documentation as such is here, which only states that it is "not guaranteed to produce a different value for each object", and "may change between framework versions". Making any assumptions about how it actually works is probably ill-advised.

Java's is more well-understood (though presumably could differ across JVMs), and is covered specifically in this question: Will .hashcode() return a different int due to compaction of tenure space?

The gist of the Java implementation is that by contract, the value of an object's hashcode is not relevant until it is retrieved for the first time. After that, it must remain constant. Thus the GC moving the object doesn't matter until the object's hashcode() method is called for the first time. After that, a cached value is used.

The identityHashCode does not change for an object. So any moving is done beneath that level.

A rudimentary implementation would have a logical address --> physical address mapping for every object.

More sophisticated implementations would only have the mapping at a page level, so perhaps the last 6 bits is the memory offset, and the rest are the page id. The indirection would happen at the page id --> actual page address level.

Osama Javed

In .net the getHash() method will be impacted by the GC and therefore its recommended that developers use their own hash implementations. I cant find the link to the internal implementation at them moment. I will post it later if I find it..

Found the link... This question was answered here

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!