java多線程之-CAS無鎖-unsafe理解

1.背景

這一節我們來學習一下unsafe對象

2.案例

1.自定義一個獲取unsafe對象的類

package com.ldp.demo07Unfase;

import sun.misc.Unsafe;
import java.lang.reflect.Field;
/**
 * @author 姿勢帝-博客園
 * @address https://www.cnblogs.com/newAndHui/
 * @WeChat 851298348
 * @create 02/19 10:17
 * @description
 */
public class MyUnsafeAccessor {
    static Unsafe unsafe;

    static {
        try {
            //  Unsafe 對象中的 private static final Unsafe theUnsafe;
            Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
            theUnsafe.setAccessible(true);
            unsafe = (Unsafe) theUnsafe.get(null);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    public static Unsafe getUnsafe() {
        return unsafe;
    }
}

 

2.定義一個普通的業務對象

@Data
@Accessors(chain = true)
public class User {
    private int id;
    private String name;
    private Integer age;
}

 

3.測試

/**
     * 測試自定義的unsafe對象
     * <p>
     * 輸出結果:
     * User(id=100, name=張無忌, age=18)
     *
     * @param args
     * @throws NoSuchFieldException
     */
    public static void main(String[] args) throws NoSuchFieldException {
        // 反射獲取字段
        Field idField = User.class.getDeclaredField("id");
        Field nameField = User.class.getDeclaredField("name");
        Field ageField = User.class.getDeclaredField("age");

        Unsafe unsafe = MyUnsafeAccessor.getUnsafe();
        // 獲取成員變量的偏移量
        long idOffset = unsafe.objectFieldOffset(idField);
        long nameOffset = unsafe.objectFieldOffset(nameField);
        long ageOffset = unsafe.objectFieldOffset(ageField);

        User user = new User();
        // 使用CAS替換值
        unsafe.compareAndSwapInt(user, idOffset, 0, 100);
        unsafe.compareAndSwapObject(user, nameOffset, null, "張無忌");
        unsafe.compareAndSwapObject(user, ageOffset, null, 18);

        // 輸出對象,看值是否設置正確
        System.out.println(user);
    }

 

完美!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章