net.dongliu.commons.async.Unsafes Maven / Gradle / Ivy
package net.dongliu.commons.async;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.Unsafe;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
/**
* utils methods to deal with Unsafe.
*
* @author Dong Liu
*/
public class Unsafes {
private static final Unsafe UNSAFE;
private static Logger logger = LoggerFactory.getLogger(Unsafes.class);
static {
Unsafe unsafe = null;
try {
for (Field field : Unsafe.class.getDeclaredFields()) {
if (field.getType() == Unsafe.class &&
(field.getModifiers() & (Modifier.FINAL | Modifier.STATIC))
== (Modifier.FINAL | Modifier.STATIC)) {
field.setAccessible(true);
unsafe = (Unsafe) field.get(null);
break;
}
}
} catch (Throwable t) {
logger.error("", t);
}
if (unsafe == null) {
// logger
throw new RuntimeException("Unsafe not supported.");
}
UNSAFE = unsafe;
}
public static Unsafe getUnsafe() {
return UNSAFE;
}
}