Unsafe使用示例

unsafe获取数组元素,并保证为volatile

getIntVolatile获取对象int值,保证为volatile类型?

@Test
    public void testUnsafeIntVolatile() throws Exception {
        // 1.获取unsafe
        Field field = Unsafe.class.getDeclaredField("theUnsafe");
        field.setAccessible(true);
        sun.misc.Unsafe unsafe = (Unsafe) field.get(null);
        // 2.获取int[]数组的元素起始位置、及每个元素占用字节数
        Class ak = int[].class;
        int ABASE = unsafe.arrayBaseOffset(ak);
        int scale = unsafe.arrayIndexScale(ak);
        System.out.println("abase:" + ABASE);
        System.out.println("scale:" + scale);

        int[] arr = new int[64];
        for (int i = 0; i < 64; i++) {
            arr[i] = i;
        }

        for (int i = 0; i < 64; i++) {
            // 获取arr里面第i个元素的值
            int val = unsafe.getIntVolatile(arr, i * 4 + 16);
            System.out.println(val);
        }
    }

你可能感兴趣的:(java,数据结构)