Created
December 19, 2011 19:21
-
-
Save akandratovich/1498488 to your computer and use it in GitHub Desktop.
Unsafe utility class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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