-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Affected files: inbox/使用 Unsafe 原子性更新对象成员值.md
- Loading branch information
Showing
1 changed file
with
59 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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); | ||
} | ||
} | ||
``` |