并发学习记录12:Unsafe

概述

Unsafe对象提供了非常底层的操作内存和线程的方法,Unsafe对象不能直接调用,只能通过反射获得

通过反射获得unsafe对象:

//通过反射获得unsafe对象
public class UnsafeTest01 {
    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
        theUnsafe.setAccessible(true);
        Unsafe unsafe = (Unsafe) theUnsafe.get(null);
        System.out.println(unsafe);
    }
}

Unsafe的CAS操作

class Student {
    volatile int id;
    volatile String name;

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}


public class UnsafeTest02 {
    public static void main(String[] args) throws NoSuchFieldException {
        Unsafe unsafe = UnsafeAccessor.getUnsafe();
        Field id = Student.class.getDeclaredField("id");
        Field name = Student.class.getDeclaredField("name");
        long idOffset = unsafe.objectFieldOffset(id);
        long nameOffset = unsafe.objectFieldOffset(name);
        Student student = new Student();
        //利用unsafe类中的函数对某个实例的属性做cas操作
        unsafe.compareAndSwapInt(student, idOffset, 0, 1);
        unsafe.compareAndSwapObject(student, nameOffset, null, "lalala");
        System.out.println(student);
    }
}
posted @ 2022-09-11 20:43  理塘DJ  阅读(19)  评论(0)    收藏  举报