Java Unsafe类的使用

Field f = Unsafe.class.getDeclaredField("theUnsafe");
f.setAccessible(true);
Unsafe unsafe = (Unsafe) f.get(null);
System.out.println(unsafe);

User user = new User(1,"aa");
System.out.println("id=" + user.getId());
Field field = user.getClass().getDeclaredField("id");
long l = unsafe.objectFieldOffset(field);
System.out.println(l);
unsafe.compareAndSwapInt(user,l,1,2);
System.out.println("id=" +user.getId());

public class User {
    private int id;
    private String name;
    public User(int id,String name) {
        this.id = id;
        this.name = name;
    }
    public int getId() {
        return id;
    }
}

 

posted on 2018-12-21 15:44  _故乡的原风景  阅读(725)  评论(0编辑  收藏  举报