Unsafe
Unsafe 对象提供了非常底层的,操作内存、线程的方法,Unsafe 对象不能直接调用,只能通过反射获得
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| public class UnsafeAccessor { static Unsafe unsafe; static { try { Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe"); theUnsafe.setAccessible(true); unsafe = (Unsafe) theUnsafe.get(null); } catch (NoSuchFieldException | IllegalAccessException e) { throw new Error(e); } } static Unsafe getUnsafe() { return unsafe; } }
|
Unsafe CAS 操作
1 2 3 4 5
| @Data class Student { volatile int id; volatile String name; }
|
1 2 3 4 5 6 7 8 9 10 11 12
| Unsafe unsafe = UnsafeAccessor.getUnsafe(); Field id = Student.class.getDeclaredField("id"); Field name = Student.class.getDeclaredField("name");
long idOffset = UnsafeAccessor.unsafe.objectFieldOffset(id); long nameOffset = UnsafeAccessor.unsafe.objectFieldOffset(name); Student student = new Student();
UnsafeAccessor.unsafe.compareAndSwapInt(student, idOffset, 0, 20); UnsafeAccessor.unsafe.compareAndSwapObject(student, nameOffset, null, "张三"); System.out.println(student);
|
输出: