Unsafe
类提供了直接操作内存、执行不安全操作和其他一些底层功能的方法,它是 JDK 中的一个特殊类,一般情况下不建议直接使用。以下是 JDK 8 中 Unsafe
类的部分源代码:
public final class Unsafe {
private Unsafe() {}
public static Unsafe getUnsafe() {
throw new SecurityException("Unsafe");
}
public native int getInt(Object o, long offset);
public native void putInt(Object o, long offset, int x);
public native Object getObject(Object o, long offset);
public native void putObject(Object o, long offset, Object x);
public native long objectFieldOffset(Field f);
public native int arrayBaseOffset(Class<?> arrayClass);
public native int arrayIndexScale(Class<?> arrayClass);
public native int getIntVolatile(Object o, long offset);
public native void putIntVolatile(Object o, long offset, int x);
public native Object getObjectVolatile(Object o, long offset);
public native void putObjectVolatile(Object o, long offset, Object x);
public native void putOrderedInt(Object o, long offset, int x);
public native void putOrderedObject(Object o, long offset, Object x);
public native boolean compareAndSwapInt(Object o, long offset, int expected, int x);
public native boolean compareAndSwapObject(Object o, long offset, Object expected, Object x);
public native void putIntAcquire(Object o, long offset, int x);
public native void putObjectAcquire(Object o, long offset, Object x);
public native int getIntAcquire(Object o, long offset);
public native Object getObjectAcquire(Object o, long offset);
public native void putIntRelease(Object o, long offset, int x);
public native void putObjectRelease(Object o, long offset, Object x);
public native int getIntVolatile(Object o, long offset);
public native void putIntVolatile(Object o, long offset, int x);
public native boolean compareAndSwapInt(Object o, long offset, int expected, int x);
public native void park(boolean isAbsolute, long time);
public native void unpark(Object thread);
public native int getLoadAverage(double[] loadavg, int nelems);
public native void loadFence();
public native void storeFence();
public native void fullFence();
}
Unsafe
类的方法可以直接操作内存,例如获取和设置对象的字段值、获取数组元素的偏移量、执行原子操作等。由于其直接操作内存的特性,使用不当可能导致程序出现严重的问题,如内存泄漏、数据不一致等。因此,一般情况下不建议直接使用 Unsafe
类。