net.dongliu.commons.lang.Unsafes Maven / Gradle / Ivy
package net.dongliu.commons.lang;
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;
}
/**
* get unsafe instance
*
* @return unsafe class instance. may be null if failed
*/
public static Unsafe getUnsafe() {
return UNSAFE;
}
}