java 变量地址_java中打印变量地址

importsun.misc.Unsafe;importjava.lang.reflect.Field;importjava.util.Arrays;importjava.util.Collections;public classOrderOfObjectsAfterGCMain {static final Unsafe unsafe =getUnsafe();static final boolean is64bit = true; //auto detect if possible.

public static voidmain(String... args) {

Double[] ascending= new Double[16];for(int i=0;i

ascending[i]= (double) i;

Double[] descending= new Double[16];for(int i=descending.length-1; i>=0; i--)

descending[i]= (double) i;

Double[] shuffled=new Double[16];for(int i=0;i

shuffled[i]= (double) i;

Collections.shuffle(Arrays.asList(shuffled));

System.out.println("Before GC");

printAddresses("ascending", ascending);

printAddresses("descending", descending);

printAddresses("shuffled", shuffled);

System.gc();

System.out.println("\nAfter GC");

printAddresses("ascending", ascending);

printAddresses("descending", descending);

printAddresses("shuffled", shuffled);

System.gc();

System.out.println("\nAfter GC 2");

printAddresses("ascending", ascending);

printAddresses("descending", descending);

printAddresses("shuffled", shuffled);

}public static voidprintAddresses(String label, Object... objects) {

System.out.print(label+ ": 0x");long last = 0;int offset =unsafe.arrayBaseOffset(objects.getClass());int scale =unsafe.arrayIndexScale(objects.getClass());switch(scale) {case 4:long factor = is64bit ? 8 : 1;final long i1 = (unsafe.getInt(objects, offset) & 0xFFFFFFFFL) *factor;

System.out.print(Long.toHexString(i1));

last=i1;for (int i = 1; i < objects.length; i++) {final long i2 = (unsafe.getInt(objects, offset + i * 4) & 0xFFFFFFFFL) *factor;if (i2 >last)

System.out.print(", +" + Long.toHexString(i2 -last));elseSystem.out.print(", -" + Long.toHexString( last -i2));

last=i2;

}break;case 8:throw new AssertionError("Not supported");

}

System.out.println();

}private staticUnsafe getUnsafe() {try{

Field theUnsafe= Unsafe.class.getDeclaredField("theUnsafe");

theUnsafe.setAccessible(true);return (Unsafe) theUnsafe.get(null);

}catch(Exception e) {throw newAssertionError(e);

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值