UnSafe类初探
package com.fjl;
import java.lang.reflect.Field;
import sun.misc.Unsafe;
class A{
private String name;
public A(String name) {
this.name = name;
}
@Override
public String toString() {
return this.name;
}
}
@SuppressWarnings("restriction")
public class TestUnsafe {
static final Unsafe unsafe;
static final long stateOffset;
private volatile long state=0;
private volatile A a=new A("a1");
static {
// unsafe=getUnsafe();
// stateOffset=get();
try {
Field field = Unsafe.class.getDeclaredField("theUnsafe");
field.setAccessible(true);
unsafe = (Unsafe)field.get(null);
// stateOffset =unsafe.objectFieldOffset(TestUnsafe.class.getDeclaredField("state"));
stateOffset =unsafe.objectFieldOffset(TestUnsafe.class.getDeclaredField("a"));
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
throw new RuntimeException(e);
// unsafe = null;a
// stateOffset =0l;
}
}
private static Unsafe getUnsafe() {
try {
Field field = Unsafe.class.getDeclaredField("theUnsafe");
field.setAccessible(true);
return (Unsafe)field.get(null);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// TODO Auto-generated method stub
return null;
}
private static long get() {
// TODO Auto-generated method stub
try {
return unsafe.objectFieldOffset(TestUnsafe.class.getDeclaredField("a"));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 0L;
}
public static void main(String[] args) {
TestUnsafe t = new TestUnsafe();
Long i=t.state;
// unsafe.compareAndSwapInt(t, stateOffset, 0, 1);
System.out.println(t.a);
A a3=t.a;
System.out.println(stateOffset);
boolean compareAndSwapObject = unsafe.compareAndSwapObject(t, stateOffset, a3, new A("a2"));
System.out.println("compareAndSwapObject="+compareAndSwapObject);
// System.out.println(t.state);
// System.out.println(i);
System.out.println(t.a);
System.out.println(a3);
}
}

- 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
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84