除了强引用之外,还有三种不同的“*引用”:WeakReference、SoftReference 和 PhantomReference。可能还有其他的,但它们要么扩展其中一个,要么与我的问题无关。
如果一个对象在 GC 循环期间不是强可达的,它就会被垃圾收集(即完成并从内存中删除)。但在它被收集之前,任何 *Reference 都会被清除——这取决于可达性条件、要清除的 *Reference 的类型、内存需求等。
我想知道,如果 JLS 对同一对象的所有同类 * 引用是否被自动/同时清除,或者是否有很小的机会(即“竞争条件”)做出任何保证,那么一些*引用被清除,而其他同类*引用则没有,这样一个对象可能会通过剩余的*引用之一恢复(即再次被强烈引用),尽管一些同类*引用已经被清除并入队。
从不同的 POV 改写的问题:假设已清除的 *Reference 意味着先前引用的对象不能通过同类的不同 *Reference 恢复是否安全?
最佳答案
您可以引用文档。
[The garbage collector] may choose to clear atomically all soft references to that object and all soft references to any other softly-reachable objects from which that object is reachable through a chain of strong references.
[The garbage collector] will atomically clear all weak references to that object and all weak references to any other weakly-reachable objects from which that object is reachable through a chain of strong and soft references.
这一点对于 PhantomReference
没有实际意义因为无法从中检索引用对象(get
始终返回 null)。
关于java - Weak/Soft/Phantom Reference清算的并发保证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28573166/