深度分析Java中如何打印对象内存地址,纠正网上很多错误的说法

先看一个简单的程序,一般我们打印对象,大部分是下面的情况,可能会重写下toString()方法,这个另说

Frolan frolan = new Frolan();

System.out.println(frolan);

// 输出结果

com.test.admin.entity.Frolan@2b80d80f

这个结果其实是调用了Object.toString打印出来的,就是类路径名+@+hashCode的16进制数

public String toString() {

return getClass().getName() + "@" + Integer.toHexString(hashCode());

}

这里的hashCode()是一个native方法,就是我们要的地址值?

我们通过源码来分析一波

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(obj) >> 3 ;

value = addrBits ^ (addrBits >> 5) ^ GVars.stwRandom ;

} else

if (hashCode == 2) {

value = 1 ; // for sensitivity testing

} else

if (hashCode == 3) {

value = ++GVars.hcSequence ;

} else

if (hashCode == 4) {

value = cast_from_oop(obj) ;

} else {

// Marsaglia's xor-shift scheme with thread-specific state

// This is probably the best overall implementation -- we'll

// likely make this the default in future releases.

unsigned t = Self->_hashStateX ;

t ^= (t << 11) ;

Self->_hashStateX = Self->_hashStateY ;

Self->_hashStateY = Self->_hashStateZ ;

Self->_hashStateZ = Self->_hashStateW ;

unsigned v = Self->_hashStateW ;

v = (v ^ (v >> 19)) ^ (t ^ (t >> 8)) ;

Self->_hashStateW = v ;

value = v ;

}

value &= markOopDesc::hash_mask;

if (value == 0) value = 0xBAD ;

assert (value != markOopDesc::no_hash, "invariant") ;

TEVENT (hashCode: GENERATE) ;

return value;

}

大概意思就是,会根据不同的hashCode返回不同的结果hashCode=0,返回随机数hashCode=1,将oop的地址做位运算、异或运算得到的结果hashCode=2,固定值1hashCode=3,返回递增序列当前值hashCode=4,oop的地址hashCode=其他值,简单理解为移位寄存器,线程安全

我们设置JVM启动参数来模拟一下

// -XX:hashCode=2

for (int i = 0; i < 3; i++) {

Frolan frolan = new Frolan();

System.out.println(frolan.hashCode());

}

// 输出结果

1

1

1

// -XX:hashCode=3

for (int i = 0; i < 3; i++) {

Frolan frolan = new Frolan();

System.out.println(frolan.hashCode());

}

// 输出结果

714

715

716

我们模拟了hashCode=2和3的情况,其它情况没那么好验证,感兴趣的话,后续大家一起交流下~

那么我们不设置启动参数,默认值是什么?

java -XX:+PrintFlagsFinal -version | grep hashCode

intx hashCode = 5 {product}

java version "1.8.0_101"

Java(TM) SE Runtime Environment (build 1.8.0_101-b13)

Java HotSpot(TM) 64-Bit Server VM (build 25.101-b13, mixed mode)

可以看到默认值是5,所以我们不设置的情况下,打印的并不是对象的内存地址

网上很多说,hashCode=4,这里就是对象的内存地址,这个是错的,这里拿到的只是oop的地址,System.identityHashCode()方法拿到的也是这个地址

如果想要获取真正的对象地址,可以使用Java 对象布局 ( JOL ) 工具

引入依赖

org.openjdk.jol

jol-core

0.9

Frolan frolan = new Frolan();

System.out.println(VM.current().addressOf(frolan));

// 输出结果

31867940040

查看原文