bss36504
bss36504

Reputation: 133

Java Soft References

Suppose I have three objects, A, B and C.

A refers to B with a soft reference.
B refers to A with a strong reference.
B also refers to C with a strong reference.
C also refers to B with a strong reference.
C also refers to A with a strong reference.

Let us assume that there are no external references to B or C. If we imagine a situation where the garbage collector decides that if it can, it will try and release memory pointed to by soft references, will B and C be released, leaving A? Or does some sort of circular dependency occur where the back-links from B and C to A somehow prevent garbage collection from happening? My understanding is that the GC should collect soft-references before OutOfMemory is thrown.

This is a highly memory intensive application that models a very large hierarchy, and as such I want the GC to discard "branches" of the hierarchy so long as there are no strong references to them. I can regenerate the branches when necessary, but that is computationally expensive, thus I implemented a cache using soft references. My general strategy is to have soft references pointing downstream (i.e. to sub-nodes of the tree) and strong references pointing back up to the parent nodes.

Upvotes: 1

Views: 100

Answers (2)

Nayuki
Nayuki

Reputation: 18552

We assume that there is an external strong reference to object A. (i.e. some "root" object points to A.)

By definition, object B is softly reachable because there is no chain of strong references to reach B, but there is a chain that consists of strong and soft references to reach B. Thus B can be garbage collected at the JVM's discretion.

Similarly, object C is not strongly reachable but is softly reachable, thus it can also be garbage collected in the same manner as B.

Due to the definition of reaching objects from the root, the fact that B and C form a cycle makes no difference whatsoever. Java uses fully general tracing garbage collection (mark-and-sweep or copying), which is immune to reference cycles that refcount-based garbage collections suffer from.

enter image description here

Upvotes: 3

Darth Android
Darth Android

Reputation: 3502

Hard references pointing back up the tree will not stop B and C from being collected.

Upvotes: 2

Related Questions