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

  1. public class UnsafeAccessor {
  2. static Unsafe unsafe;
  3. static {
  4. try {
  5. Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
  6. theUnsafe.setAccessible(true);
  7. unsafe = (Unsafe) theUnsafe.get(null);
  8. } catch (NoSuchFieldException | IllegalAccessException e) {
  9. throw new Error(e);
  10. }
  11. }
  12. static Unsafe getUnsafe() {
  13. return unsafe;
  14. }
  15. }

Unsafe CAS 操作

  1. public class TestUnsafe {
  2. public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
  3. Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
  4. theUnsafe.setAccessible(true);
  5. Unsafe unsafe = (Unsafe) theUnsafe.get(null);
  6. System.out.println(unsafe);
  7. // 1. 获取域的偏移地址
  8. long idOffset = unsafe.objectFieldOffset(Teacher.class.getDeclaredField("id"));
  9. long nameOffset = unsafe.objectFieldOffset(Teacher.class.getDeclaredField("name"));
  10. Teacher t = new Teacher();
  11. // 2. 执行 cas 操作
  12. unsafe.compareAndSwapInt(t, idOffset, 0, 1);
  13. unsafe.compareAndSwapObject(t, nameOffset, null, "张三");
  14. // 3. 验证
  15. System.out.println(t);
  16. }
  17. }
  18. @Data
  19. class Teacher {
  20. volatile int id;
  21. volatile String name;
  22. }