Skip to content

Instantly share code, notes, and snippets.

@akandratovich
Created December 19, 2011 19:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akandratovich/1498488 to your computer and use it in GitHub Desktop.
Save akandratovich/1498488 to your computer and use it in GitHub Desktop.
Unsafe utility class
import java.lang.reflect.Field;
import sun.misc.Unsafe;
public class T {
public static Unsafe u;
private static long fieldOffset;
private static T instance = new T();
private Object obj;
static {
try {
Field f = Unsafe.class.getDeclaredField("theUnsafe");
f.setAccessible(true);
u = (Unsafe) f.get(null);
fieldOffset = u.objectFieldOffset(T.class.getDeclaredField("obj"));
} catch (Exception ex) {
throw new RuntimeException(ex);
}
};
public synchronized static long o2a(Object o) {
instance.obj = o;
return u.getLong(instance, fieldOffset);
}
public synchronized static Object a2o(long address) {
u.putLong(instance, fieldOffset, address);
return instance.obj;
}
public static Unsafe get() {
return u;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment