Java Reference
In-Depth Information
In use
in use
object name (ref count)
Figure 6.1 Some garbage collectors manage memory by counting references. Here, the objects
with a reference count of 0 will be identified by the garbage collector and freed. Notice that
objects D and G are not in use but will not be freed, due to a circular reference.
The problem with reference-counting garbage collection is that it cannot
detect cycles , or objects that reference each other, though they might not be in
use by any other object. In fact, we couldn't use the objects below the line if
we wanted to, because we no longer have a reference. In our example, objects
E and F would be freed, but D and G would not. D and G have positive refer-
ence counts, though we cannot possibly use them. This short program dem-
onstrates an object that would be freed, and one that would not:
Listing 6.1
Demonstrating a circular reference
public class LinkedList o Linked list class
public LinkedList next = null;
public someMethod () {
LinkedList a = new LinkedList();
LinkedList b = new LinkedList(); = b; = a;
a = null;
o Allocate A/B.
A/B reference counters = 1 .
o A/B reference B/A.
A/B reference counters = 2.
b = null;
o Remove references to A/B.
A/B reference counters = 1 .
Search WWH ::

Custom Search