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
public class Dog {
private String name;
private int age;

public Dog(){
this.name = null;
this.age = 0;
}

public Dog(String name, int age){
this.age = age;
this.name = name;
}

@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
public class Test {
public 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 {
Test test = new Test();
Unsafe unsafe = test.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,3);
System.out.println(dog.toString());
}
}

操作数组

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
public class Test1 {
public 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 {
Test1 test = new Test1();
Unsafe unsafe = test.getUnsafe();
//帮助理解concurrentHashmap
Dog[] dogs = new Dog[3];
//获取数组中第一个元素的偏移量
long dogBase = unsafe.arrayBaseOffset(Dog[].class);
//获取数组中一个元素的大小
int ts = unsafe.arrayIndexScale(Dog[].class);
int dogShift = 31 - Integer.numberOfLeadingZeros(ts);
unsafe.putOrderedObject(dogs, dogBase, new Dog("旺财",3));
unsafe.putOrderedObject(dogs, (long)(1 << dogShift) + dogBase, new Dog("小强",4));
unsafe.putOrderedObject(dogs, ts*2 + dogBase, new Dog("富贵", 5));
for(int i = 0 ; i < dogs.length ; i++){
System.out.println(dogs[i].toString());
}
}
}
看官可在此打赏