JEP 260是Java9中一项重要内容,意在封装那些JDK内部使用的API,而不再提供给外部应用使用。 鉴于类似Unsafe这类非常关键而广泛使用的API,目前也没有非常有效的替代方案,暂时得到了保留,因此在JDK9中,我们仍然可以使用Unsafe类,目前没有被内部封装。 在JDK9中jdk.internal.misc中也可以找到Unsafe类。
private static final Unsafe theUnsafe = new Unsafe();
/** * Provides the caller with the capability of performing unsafe * operations. * * <p>The returned {@code Unsafe} object should be carefully guarded * by the caller, since it can be used to read and write data at arbitrary * memory addresses. It must never be passed to untrusted code. * * <p>Most methods in this class are very low-level, and correspond to a * small number of hardware instructions (on typical machines). Compilers * are encouraged to optimize these methods accordingly. * * <p>Here is a suggested idiom for using unsafe operations: * * <pre> {@code * class MyTrustedClass { * private static final Unsafe unsafe = Unsafe.getUnsafe(); * ... * private long myCountAddress = ...; * public int getCount() { return unsafe.getByte(myCountAddress); } * }}</pre> * * (It may assist compilers to make the local variable {@code final}.) */ public static Unsafe getUnsafe() { return theUnsafe; }
private static final Unsafe theUnsafe = new Unsafe(); private static final jdk.internal.misc.Unsafe theInternalUnsafe = jdk.internal.misc.Unsafe.getUnsafe();
/** * Provides the caller with the capability of performing unsafe * operations. * * <p>The returned {@code Unsafe} object should be carefully guarded * by the caller, since it can be used to read and write data at arbitrary * memory addresses. It must never be passed to untrusted code. * * <p>Most methods in this class are very low-level, and correspond to a * small number of hardware instructions (on typical machines). Compilers * are encouraged to optimize these methods accordingly. * * <p>Here is a suggested idiom for using unsafe operations: * * <pre> {@code * class MyTrustedClass { * private static final Unsafe unsafe = Unsafe.getUnsafe(); * ... * private long myCountAddress = ...; * public int getCount() { return unsafe.getByte(myCountAddress); } * }}</pre> * * (It may assist compilers to make the local variable {@code final}.) * * @throws SecurityException if the class loader of the caller * class is not in the system domain in which all permissions * are granted. */ @CallerSensitive public static Unsafe getUnsafe() { Class<?> caller = Reflection.getCallerClass(); if (!VM.isSystemDomainLoader(caller.getClassLoader())) throw new SecurityException("Unsafe"); return theUnsafe; }