其他分享
首页 > 其他分享> > 并发学习记录12:Unsafe

并发学习记录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);
    }
}

标签:12,name,Unsafe,unsafe,class,并发,Student,id
来源: https://www.cnblogs.com/wbstudy/p/16683558.html