gpt4 book ai didi

java - 有人可以解释强、软、弱和幻影引用之间的区别及其用法吗?

转载 作者:IT老高 更新时间:2023-10-28 21:08:56 28 4
gpt4 key购买 nike

我一直试图理解不同引用文献之间的区别,但该理论并没有激发任何想法让我将其形象化。

谁能简要解释一下不同的引用文献?

每个人都有一个例子会做得更好。

最佳答案

关于该主题的另一篇好文章:
Java Reference Objects or How I Learned to Stop Worrying and Love OutOfMemoryError ,有漂亮的图表

http://www.kdgregory.com/images/java.refobj/object_life_cycle_with_refobj.gif

摘录:

As you might guess, adding three new optional states to the object life-cycle diagram makes for a mess.
Although the documentation indicates a logical progression from strongly reachable through soft, weak, and phantom, to reclaimed, the actual progression depends on what reference objects your program creates.
If you create a WeakReference but don't create a SoftReference, then an object progresses directly from strongly-reachable to weakly-reachable to finalized to collected. object life-cycle, with reference objects

同样重要的是请记住,并非所有对象都附加到引用对象 - 事实上,它们中应该很少有
引用对象是一个间接层:您通过引用对象到达被引用对象,显然您不希望在整个代码中使用该层间接。
事实上,大多数程序会使用引用对象来访问程序创建的相对少量的对象。

引用文献和引用文献

引用对象在您的程序代码和其他对象(称为引用对象)之间提供了一个间接层。
每个引用对象都是围绕其所指对象构造的,并提供一个 get() 方法来访问所指对象。创建引用后,您无法更改其引用。收集到所指对象后,get() 方法将返回 null。应用程序代码、软/弱引用和引用对象之间的关系

alt text


更多示例:Java Programming: References' Package

alt text http://www.pabrantes.net/blog/space/start/2007-09-16/1/referenceTypes.png

  • Case 1: This is the regular case where Object is said to be strongly reachable.

  • Case 2: There are two paths to Object, so the strongest one is chosen, which is the one with the strong reference hence the object is strongly reachable.

  • Case 3: Once again there are two paths to the Object, the strongest one is the Weak Reference (since the other one is a Phantom Reference), so the object is said to be weakly reachable.

  • Case 4: There is only one path and the weakest link is a weak reference, so the object is weakly reachable.

  • Case 5: Only one path and the weakest link is the phantom reference hence the object is phantomly reachable.

  • Case 6: There are now two paths and the strongest path is the one with a soft reference, so the object is now said to be softly reachable.

关于java - 有人可以解释强、软、弱和幻影引用之间的区别及其用法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2012790/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com