All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.dongliu.commons.lang.Unsafes Maven / Gradle / Ivy

There is a newer version: 1.0.9
Show newest version
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;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy