fork download
  1. import java.util.ArrayList;
  2. import java.util.List;
  3.  
  4. import sun.misc.Unsafe;
  5. import java.lang.reflect.Field;
  6.  
  7. class HelloWorld
  8. {
  9.  
  10. static final Unsafe unsafe = getUnsafe();
  11. static final boolean is64bit = true;
  12.  
  13. private static class OBJ {
  14. int one;
  15. String two;
  16.  
  17. public OBJ() {
  18. this.one = 1;
  19. this.two = "two";
  20. }
  21. }
  22.  
  23. public static void do_it(OBJ o) {
  24. System.out.println("o.two is: " + o.two);
  25. }
  26.  
  27. public static void main(String[] args)
  28. {
  29.  
  30. System.out.println("start");
  31.  
  32. List<OBJ> list = new ArrayList<>();
  33. list.add(new OBJ());
  34. list.add(new OBJ());
  35. list.add(new OBJ());
  36.  
  37. OBJ x = list.get(2);
  38.  
  39. printAddresses("Address x", x);
  40.  
  41. for (int idx = 0; idx < 1000000; idx++) {
  42. list.add(new OBJ());
  43. }
  44.  
  45. OBJ x2 = list.get(2);
  46. x2.two = "haha";
  47.  
  48. printAddresses("Address x", x);
  49.  
  50. do_it(x);
  51.  
  52. }
  53.  
  54. public static void printAddresses(String label, Object... objects) {
  55. System.out.print(label + ": 0x");
  56. long last = 0;
  57. int offset = unsafe.arrayBaseOffset(objects.getClass());
  58. int scale = unsafe.arrayIndexScale(objects.getClass());
  59. switch (scale) {
  60. case 4:
  61. long factor = is64bit ? 8 : 1;
  62. final long i1 = (unsafe.getInt(objects, offset) & 0xFFFFFFFFL) * factor;
  63. System.out.print(Long.toHexString(i1));
  64. last = i1;
  65. for (int i = 1; i < objects.length; i++) {
  66. final long i2 = (unsafe.getInt(objects, offset + i * 4) & 0xFFFFFFFFL) * factor;
  67. if (i2 > last)
  68. System.out.print(", +" + Long.toHexString(i2 - last));
  69. else
  70. System.out.print(", -" + Long.toHexString( last - i2));
  71. last = i2;
  72. }
  73. break;
  74. case 8:
  75. throw new AssertionError("Not supported");
  76. }
  77. System.out.println();
  78. }
  79.  
  80. private static Unsafe getUnsafe() {
  81. try {
  82. Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
  83. theUnsafe.setAccessible(true);
  84. return (Unsafe) theUnsafe.get(null);
  85. } catch (Exception e) {
  86. throw new AssertionError(e);
  87. }
  88. }
  89. }
  90.  
Success #stdin #stdout 0.45s 320512KB
stdin
Standard input is empty
stdout
start
Address x: 0x525554440
Address x: 0x550882b80
o.two is: haha