sun.misc.Unsafe在JDK9里变成了public?

Is sun.misc.Unsafe become public in JDK9?

我刚刚尝试了 JDK9,发现 sun.misc.Unsafe 现在不包含本地方法,而是将它们委托给某些 jdk.internal.misc.Unsafe,例如:

@ForceInline
public int getInt(Object o, long offset) {
    return theInternalUnsafe.getInt(o, offset);
}

反过来,最新的看起来实际上像旧的 sun.misc.Unsafe,但现在这些方法带有一些注释:

@HotSpotIntrinsicCandidate
public native void putObject(Object o, long offset, Object x);

那么,是"safe"使用Unsafe启动JDK9吗?现在是public官方API吗?

这里有一个很好的解释:

https://adtmag.com/blogs/watersworks/2015/08/java-9-hack.aspx

What to do with sun.misc.Unsafe in Java 9? One side says it's simply an awful hack from the bad old days that should be gotten rid of; the other side says its heavy use is responsible for the rise of Java in the infrastructure space and popular tools still need it. The problem is, both sides are right. ...

Writing on the OpenJDK mailing list, Reinhold proposed encapsulating unsupported, internal APIs, including sun.misc.Unsafe, within modules that define and use them. That proposal is now a formal Java Enhancement Proposals (JEP). Posted this week, JEP 260 ("Encapsulate Most Internal APIs") aims to "make most of the JDK's internal APIs inaccessible by default, but leave a few critical, widely used internal APIs accessible, until supported replacements exist for all or most of their functionality."

简短回答:您不应该在您从头开发的任何新应用程序中使用它。

的解释很好,知道要不要继续用

长答案~JEP 260: Encapsulate Most Internal APIs


Why did they decide over removing/deprecating the support of an API used for long?

实用性

The Modular JDKJEP 200, limiting access to non-standard, unstable, and unsupported APIs that are internal implementation details of the JDK by leveraging The Module SystemJEP 261 提高了平台的完整性和安全性 因为其中许多内部 API定义特权的、安全敏感的操作。从长远来看 运行, 此更改将减少 JDK 本身以及有意或无意使用的库和应用程序的维护者 承担的成本这些内部 APIs.


Are all the internal APIs planned to be encapsulated?

类别

上面指定的JDK的内部API分为两大类:-

  • 非关键内部 APIs 似乎未被 JDK 之外的代码使用或被使用通过外部代码只是为了方便..

  • 关键内部 APIs 提供的关键功能即使不是不可能,也很难在 [=104= 之外实现] 本身(例如,sun.misc.Unsafe)。


What if someone is migrating code that already makes use of Unsafe, but eventually plans to move away?

sun.misc.Unsafe

它是那些未封装在 JDK 9 中的关键内部 API 之一,因为支持的替换在 JDK 8 中不存在,同时大多数其他 API 已封装或已弃用,将在未来的版本中删除。

Is sun.misc.Unsafe become public in JDK9?

  • 用法

    目前要访问关键的内部 API,例如 Unsafe,需要定义对 jdk.unsupported 模块的依赖,该模块专门为此目的定义:

    module jdk.unsupported {
        exports sun.misc;
        opens sun.misc;
        ...
    }
    

尽管它可以回答你的问题,但你甚至找不到这个模块documented,可能是为了限制消费者使用它并且明显是避免使用它的标志使其成为 "public".

  • 迁移

    Unsafe class 中的许多方法的功能已通过 Variable Handles JEP 193[=97= 提供].