|
| 1 | +package com.basics.UnsafeTest.unsafe_voliate; |
| 2 | + |
| 3 | +import sun.misc.Unsafe; |
| 4 | + |
| 5 | +import java.lang.reflect.Field; |
| 6 | +import java.util.ArrayList; |
| 7 | + |
| 8 | +/** |
| 9 | + * @ClassName UnsafeTestTwo |
| 10 | + * @Description TODO |
| 11 | + * @Author chenzhuo |
| 12 | + * @Date 2018/8/22 11:20 |
| 13 | + * @Version 1.0 |
| 14 | + * |
| 15 | + * pageSize :4096 |
| 16 | + * address :8 变量指针的长度(4/8 32/64系统) |
| 17 | + * anLong :12 |
| 18 | + **/ |
| 19 | +public class UnsafeTestTwo { |
| 20 | + public static Unsafe unsafe; |
| 21 | + public int anInt; |
| 22 | + public static long anLong; |
| 23 | + static { |
| 24 | + try { |
| 25 | + Field field = Unsafe.class.getDeclaredField("theUnsafe"); |
| 26 | + field.setAccessible(true); |
| 27 | + unsafe = (Unsafe) field.get(null); |
| 28 | + anLong = unsafe.objectFieldOffset(UnsafeTestTwo.class.getDeclaredField("anInt")); |
| 29 | + } catch (NoSuchFieldException e) { |
| 30 | + e.printStackTrace(); |
| 31 | + } catch (IllegalAccessException e) { |
| 32 | + e.printStackTrace(); |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + public static void main(String[] args) { |
| 37 | + UnsafeTestTwo unsafeTestTwo = new UnsafeTestTwo(); |
| 38 | + System.out.println(" pageSize :" +unsafe.pageSize()); |
| 39 | + System.out.println("address :" + unsafe.addressSize()); |
| 40 | + unsafe.putInt(UnsafeTestTwo.class,anLong,10); |
| 41 | + int unsafeInt = unsafe.getInt(UnsafeTestTwo.class, anLong); |
| 42 | + System.out.println("anInt: " + unsafeInt); |
| 43 | + System.out.println("anLong : " + anLong); |
| 44 | + unsafeTestTwo.testSys(); |
| 45 | + } |
| 46 | + |
| 47 | + public void testSys() { |
| 48 | + /* System. out. println("array scale "+unsafe .arrayIndexScale(ArrayList.class));*/ |
| 49 | + System. out . println("array scale "+unsafe. arrayIndexScale(UnsafeTestTwo[].class)); |
| 50 | + System. out . println("array scale "+unsafe. arrayIndexScale(Long.class)); |
| 51 | + System. out . println("array scale "+unsafe . arrayIndexScale(Boolean[].class)); |
| 52 | + /* System. out . println("array i scale "+unsafe. arrayIndexScale(int[]. class));*/ |
| 53 | + System. out . println("array scale"+unsafe . arrayIndexScale(Integer.class)); |
| 54 | + System. out . println("array scale "+unsafe . arrayIndexScale(Byte.class)); |
| 55 | + } |
| 56 | +} |
| 57 | + |
0 commit comments