TestUnsafe.java
package com.graker.unsafe.demos;
import org.junit.Test;
import sun.misc.Unsafe;
import java.lang.reflect.Field;
class OtherObject {
private int x;
public OtherObject(int x) {
this.x = x;
}
@Override
public String toString() {
return "OtherObject{" +
"x=" + x +
'}';
}
}
class SomeObject {
private OtherObject id;
private OtherObject obj;
public SomeObject(OtherObject i) throws NoSuchFieldException, IllegalAccessException {
Unsafe theUnsafe = UnsafeLoader.getUnsafe();
System.out.println(this.id);
if (i != null)
this.id = i;
else {
long SomeObject_idOffset = theUnsafe.objectFieldOffset(SomeObject.class.getDeclaredField("id"));
boolean ModifiedSuccess = theUnsafe.compareAndSwapObject(this,SomeObject_idOffset,null,new OtherObject(100));
System.out.println(this.id);
System.out.println(ModifiedSuccess);
}
}
@Override
public String toString() {
return "SomeObject{" +
"id=" + id +
", obj=" + obj +
'}';
}
}
public class TestUnsafe {
@Test
public void testUnsafe() throws NoSuchFieldException, IllegalAccessException {
SomeObject someObject = new SomeObject(null);
System.out.print(someObject);
}
}
UnsafeLoader.java
package com.graker.unsafe.demos;
import sun.misc.Unsafe;
import java.lang.reflect.Field;
public class UnsafeLoader {
private static Unsafe theUnsafe;
private volatile static boolean inited = false;
public UnsafeLoader() {
}
public static Unsafe getUnsafe() throws NoSuchFieldException, IllegalAccessException {
// balking
if(!inited) {
synchronized (UnsafeLoader.class) {
if (!inited) {
Field Declared = Unsafe.class.getDeclaredField("theUnsafe");
Declared.setAccessible(true);
theUnsafe = (Unsafe) Declared.get(Unsafe.class);
inited = true;
}
}
}
return theUnsafe;
}
}