From cbc20dd21c0c63b3a57a9173596f0b8a786a61ca Mon Sep 17 00:00:00 2001 From: liuyiwei <709224218@qq.com> Date: Sun, 19 Mar 2023 10:30:07 +0800 Subject: [PATCH] vault backup: 2023-03-19 10:30:07 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Affected files: inbox/使用 Unsafe 原子性更新对象成员值.md --- ...41\346\210\220\345\221\230\345\200\274.md" | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 "inbox/\344\275\277\347\224\250 Unsafe \345\216\237\345\255\220\346\200\247\346\233\264\346\226\260\345\257\271\350\261\241\346\210\220\345\221\230\345\200\274.md" diff --git "a/inbox/\344\275\277\347\224\250 Unsafe \345\216\237\345\255\220\346\200\247\346\233\264\346\226\260\345\257\271\350\261\241\346\210\220\345\221\230\345\200\274.md" "b/inbox/\344\275\277\347\224\250 Unsafe \345\216\237\345\255\220\346\200\247\346\233\264\346\226\260\345\257\271\350\261\241\346\210\220\345\221\230\345\200\274.md" new file mode 100644 index 0000000..935d121 --- /dev/null +++ "b/inbox/\344\275\277\347\224\250 Unsafe \345\216\237\345\255\220\346\200\247\346\233\264\346\226\260\345\257\271\350\261\241\346\210\220\345\221\230\345\200\274.md" @@ -0,0 +1,59 @@ +--- +date created: 2023-03-19, 10:22:08 +date modified: 2023-03-19, 10:22:16 +--- + +# Meta + +- alias: +- parent :: +- siblings :: +- child :: +- refs: + - https://stackoverflow.com/questions/13003871/how-do-i-get-the-instance-of-sun-misc-unsafe + - AQS 中的代码 + +--- + +```java +public class ReflectTest { + public static void main(String[] args) { + Student student = new Student(); + student.setState(123); + + System.out.println(student.compareAndSetState(123, 99)); + System.out.println(student.getState()); // 99 + } +} + +class Student { + private int state; + + private static final long stateOffset; + + private static final Unsafe unsafe; + + static { + try { + Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe"); + theUnsafe.setAccessible(true); + unsafe = (Unsafe) theUnsafe.get(null); + stateOffset = unsafe.objectFieldOffset(Student.class.getDeclaredField("state")); + } catch (Exception ex) { + throw new Error(ex); + } + } + + public void setState(int state) { + this.state = state; + } + + public int getState() { + return state; + } + + public final boolean compareAndSetState(int expected, int update) { + return unsafe.compareAndSwapInt(this, stateOffset, expected, update); + } +} +``` \ No newline at end of file