问:
为什么要先撤销偏向锁到无锁状态 , 再来生成hashcode呢?这跟锁有什么关系?
答:
mark word里 , hashcode存储的字节位置被偏向锁给占了!偏向锁存储了锁持有者的线程id
(参考上面的markword图)
扩展:关于hashCode的生成算法(了解)
// hashCode() generation :// 涉及到c++算法领域 , 感兴趣的同学自行研究// Possibilities:// * MD5Digest of {obj,stwRandom}// * CRC32 of {obj,stwRandom} or any linear-feedback shift register function.// * A DES- or AES-style SBox[] mechanism// * One of the Phi-based schemes, such as://2654435761 = 2^32 * Phi (golden ratio)//HashCodeValue = https://www.isolves.com/it/qt/2022-08-03/((uintptr_t(obj) >> 3) * 2654435761) ^ GVars.stwRandom ;// * A variation of Marsaglia's shift-xor RNG scheme.// * (obj ^ stwRandom) is appealing, but can result//in undesirable regularity in the hashCode values of adjacent objects//(objects allocated back-to-back, in particular).This could potentially//result in hashtable collisions and reduced hashtable efficiency.//There are simple ways to "diffuse" the middle address bits over the//generated hashCode values://static inline intptr_t get_next_hash(Thread * Self, oop obj) {intptr_t value = 0 ;if (hashCode == 0) {// This form uses an unguarded global Park-Miller RNG,// so it's possible for two threads to race and generate the same RNG.// On MP system we'll have lots of RW access to a global, so the// mechanism induces lots of coherency traffic.value = os::random() ;//返回随机数} else if (hashCode == 1) {// This variation has the property of being stable (idempotent)// between STW operations.This can be useful in some of the 1-0// synchronization schemes.//和地址相关 , 但不是地址;右移+异或算法intptr_t addrBits = cast_from_oop
5)总结通过分析虚拟机源码我们证明了hashCode不是直接用的内存地址 , 而是采取一定的算法来生成
hashcode值的存储在mark word里 , 与锁共用一段bit位 , 这就造成了跟锁状态相关性
- 如果是偏向锁:
- 那偏偏这会就是有线程硬性使用对象的锁呢?
推荐阅读
- 护士/护理人员的完整简历范文 护士简历范文
- |职场中有哪些常见的套路?
- |职场上,面子不是所谓的客气,而是让自己有了自信,让自己成功
- 养狗好处vs养狗坏处 养宠物的利弊
- 配音|余生,做一个能扛事的成年人
- 秋作文400字18篇作文 秋天的作文400字
- 翡翠手镯|翡翠手镯的价值,傻瓜教程,教你这样看懂翡翠手镯的色泽
- 短发|爱美的美女看过来,你知道秋天为什么要补水吗?
- 无基础唱歌技巧和发声方式教学 学习唱歌的方法
- 全球变暖的危害有哪些 全球变暖的后果