unsafe类了解
# unsafe类
JDK 的此jar包中 的 Unsafe 类提供了硬件级别的原子性操作 ,Unsafe 类中的方法都是native 方法 ,它们使用JNI的方式访问本地 C++实现库。
# 使用unsafe类 完成copareAndSwap
/**
* @author ggBall
* @version 1.0.0
* @ClassName UnsafeSateTest.java
* @Description 获取不到unsafe app类加载器加载不到 unsafe 因为unsafe只允许bootstrap类加载器获取,Unsafe.getUnsafe()里面也做了判断只允许bootstrap类加载器加载
* @createTime 2022年04月30日 16:44:00
*/
public class UnsafeSateTest {
static final Unsafe unSafe = Unsafe.getUnsafe();
static long stateOffset = 0;
private volatile long state = 0;
static {
try {
// 拿到 属性state在类UnsafeSateTest的偏移量
stateOffset = unSafe.objectFieldOffset(UnsafeSateTest.class.getDeclaredField("state"));
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
UnsafeSateTest unsafeSateTest = new UnsafeSateTest();
boolean result = unSafe.compareAndSwapLong(unsafeSateTest, stateOffset, 0, 1);
System.out.println("result = " + result);
}
}
/**
* @author ggBall
* @version 1.0.0
* @ClassName UnsafeSateTest.java
* @Description 利用反射获取unsafe
* @createTime 2022年04月30日 16:44:00
*/
public class UnsafeSateTest2 {
static Unsafe unSafe;
static long stateOffset = 0;
private volatile long state = 0;
static {
try {
Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
theUnsafe.setAccessible(true);
// 获取该变量的值
unSafe = (Unsafe)theUnsafe.get(null);
// 拿到 属性state在类UnsafeSateTest的偏移量
stateOffset = unSafe.objectFieldOffset(UnsafeSateTest2.class.getDeclaredField("state"));
} catch (NoSuchFieldException | IllegalAccessException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
UnsafeSateTest2 unsafeSateTest = new UnsafeSateTest2();
boolean result = unSafe.compareAndSwapLong(unsafeSateTest, stateOffset, 0, 1);
System.out.println("result = " + result);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
上次更新: 2022/05/09, 09:03:10