前几天我偶然发现了一个不安全的包装,它的功能让我感到惊讶。

当然,这个类是没有记录的,但是我想知道是否有一个很好的理由使用它。可能会出现哪些需要使用它的场景?如何在现实场景中使用它?

此外,如果您确实需要它,这难道不表明您的设计可能存在问题吗?

为什么Java包含这个类?


当前回答

对象的可用性似乎低于Java代码通常允许的级别。如果您正在编写一个高级应用程序,那么JVM将内存处理和其他操作从代码级别抽象出来,因此更容易编程。通过使用不安全库,您可以有效地完成通常由您完成的低级操作。

正如woliveirajr所述,“random()”使用Unsafe来播种,就像许多其他操作将使用Unsafe中包含的allocateMemory()函数一样。

作为程序员,你可能永远不需要这个库,但严格控制底层元素确实很方便(这就是为什么在主要产品中仍然有汇编代码和(在较小程度上)C代码的原因)

其他回答

not safe.park()和not safe.unpark()用于构建自定义并发控制结构和协作调度机制。

堆外集合对于分配大量内存并在使用后立即释放内存而不受GC干扰可能很有用。我基于sun.misc.Unsafe编写了一个用于处理堆外数组/列表的库。

I was recently working on reimplementing the JVM and found that a surprising number of classes are implemented in terms of Unsafe. The class is mostly designed for the Java library implementers and contains features that are fundamentally unsafe but necessary for building fast primitives. For example, there are methods for getting and writing raw field offsets, using hardware-level synchronization, allocating and freeing memory, etc. It is not intended to be used by normal Java programmers; it's undocumented, implementation-specific, and inherently unsafe (hence the name!). Moreover, I think that the SecurityManager will disallow access to it in almost all cases.

简而言之,它的存在主要是为了允许库实现者访问底层机器,而不必在某些类(如AtomicInteger native)中声明每个方法。在常规Java编程中不需要使用或担心它,因为重点是使其余的库足够快,从而不需要这种访问。

类不安全 用于执行低级、不安全操作的方法的集合。虽然类和所有方法都是公共的,但该类的使用是有限的,因为只有可信代码才能获得它的实例。

它的一种用法是在java.util.concurrent.atomic类中:

AtomicIntegerArray AtomicLongArray

它使用的一个例子是random方法,该方法调用不安全的方法来更改种子。

这个网站也有它的一些用途。