Luckylau's Blog

java中的Unsafe类使用

Unsafe类存在sun.misc.Unsafe中可以直接读写内存、获得地址偏移值、锁定或释放线程。concurrentHashmap的1.7版本大量使用该类来提高提升Java运行效率。下面我们介绍一下其使用。

操作成员变量

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
public class test {
public static Unsafe getUnsafe() {
try {
final Field unsafeField = Unsafe.class.getDeclaredField("theUnsafe");
unsafeField.setAccessible(true);
// the unsafe instance
return (Unsafe) unsafeField.get(null);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args)throws Exception {
Unsafe unsafe = getUnsafe();
Dog dog = new Dog();
// 获取name属性偏移量
long nameOffset = unsafe.objectFieldOffset(Dog.class.getDeclaredField("name"));
unsafe.putObject(dog, nameOffset, "李富貴");
//获取age属性偏移量
long ageOffset = unsafe.objectFieldOffset(Dog.class.getDeclaredField("age"));
unsafe.putInt(dog, ageOffset,5);
System.out.println(dog.toString());
}
}
class Dog {
private String name;
private int age;
@Override
public String toString() {
return "{\"Dog\":{"
+ " \"name\":\"" + name + "\""
+ ", \"age\":\"" + age + "\""
+ "}}";
}
}

操作数组

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
public class test {
public static Unsafe getUnsafe() {
try {
final Field unsafeField = Unsafe.class.getDeclaredField("theUnsafe");
unsafeField.setAccessible(true);
// the unsafe instance
return (Unsafe) unsafeField.get(null);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args)throws Exception {
Unsafe unsafe = getUnsafe();
//帮助理解concurrentHashmap
Dog[] dogs = new Dog[3];
long sbase = unsafe.arrayBaseOffset(Dog[].class);
int ts = unsafe.arrayIndexScale(Dog[].class);
int sshift = 31 - Integer.numberOfLeadingZeros(ts);
unsafe.putOrderedObject(dogs, (long)(0 << sshift) + sbase, new Dog("那傻狗",5));
unsafe.putOrderedObject(dogs, (long)(1 << sshift) + sbase, new Dog("李富貴",5));
unsafe.putOrderedObject(dogs, ts*2 + sbase, new Dog("哈士奇", 5));
for(int i = 0 ; i < dogs.length ; i++){
System.out.println(dogs[i].toString());
}
}
}
class Dog {
private String name;
private int age;
public Dog(String name, int age){
this.age = age;
this.name = name;
}
@Override
public String toString() {
return "{\"Dog\":{"
+ " \"name\":\"" + name + "\""
+ ", \"age\":\"" + age + "\""
+ "}}";
}
}
Luckylau wechat
如果对您有价值,看官可以打赏的!