Merge pull request #155 from jrask/android_unsafe_fix

UnsafeDetectUtil checks that the Unsafe class has the field theUnsafe
This commit is contained in:
Norman Maurer 2012-01-19 12:22:48 -08:00
commit b96768c9a6

View File

@ -15,24 +15,42 @@
*/ */
package io.netty.util; package io.netty.util;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
/** /**
* Utility which checks if {@value #UNSAFE} class can be found in the classpath * Utility which checks if {@value #UNSAFE} class can be found in the classpath
* and that it can be accessed using "theUnsafe" field which is not true for all platforms, i.e Android
* where it is called "THE_ONE".
*/ */
public final class UnsafeDetectUtil { public final class UnsafeDetectUtil {
private static final String THE_UNSAFE = "theUnsafe";
private static final String UNSAFE = "sun.misc.Unsafe"; private static final String UNSAFE = "sun.misc.Unsafe";
private static final boolean UNSAFE_FOUND = isUnsafeFound(AtomicInteger.class.getClassLoader()); private static final boolean UNSAFE_FOUND = isUnsafeFound(AtomicInteger.class.getClassLoader());
public static boolean isUnsafeFound(ClassLoader loader) { public static boolean isUnsafeFound(ClassLoader loader) {
try { try {
Class.forName(UNSAFE, true, loader); Class<?> unsafeClazz = Class.forName(UNSAFE, true, loader);
return true; return hasUnsafeField(unsafeClazz);
} catch (ClassNotFoundException e) { } catch (ClassNotFoundException e) {
return false; return false;
} } catch (SecurityException e) {
return false;
} catch (PrivilegedActionException e) {
return false;
}
}
private static boolean hasUnsafeField(final Class<?> unsafeClass) throws PrivilegedActionException {
return AccessController.doPrivileged (new PrivilegedExceptionAction<Boolean>() {
public Boolean run() throws Exception {
unsafeClass.getDeclaredField(THE_UNSAFE);
return true;
}});
} }
public static boolean isUnsafeFound() { public static boolean isUnsafeFound() {