Samir Mangroliya
Samir Mangroliya

Reputation: 40416

Why aren't Java weak references counted as references during garbage collection?

Why are Java weak references not counted as references with respect to garbage collection?

Upvotes: 1

Views: 151

Answers (2)

Kaz
Kaz

Reputation: 58627

Weak references are not counted as references under GC because that is the whole point of their existence and their definition: references that do not cause the object they point to to be considered live.

This is very useful because it lets you maintain relationships among objects which automatically go away when you are no longer interested in those objects.

You can extend objects with properties, without causing objects to become permanently linked into the reachability graph (turning into "semantic garbage" when no longer needed).

For example, a global weak hash table could let you find all of the Student objects belonging to a given Course and vice versa: all the Course objects belonging to a Student.

If a Student becomes garbage (you lose all your references to it), the weak hash table will automatically remove the entry associating that Student with its Course objects.

The advantage is that you didn't have to add a list of students into the Course class. And also, when you want to get rid of a Student, you do not have to hunt down every Course object and remove that student from its list.

Just lose track of the Student "naturally" and the weak hash table will purge itself.

Upvotes: 4

aioobe
aioobe

Reputation: 421220

Because that is simply its purpose.

An object is garbage collected if 0 references are pointing at it. Since a weak reference should not, on its own, prevent an object from being garbage collected, it is not counted during GC.

Have a look at the various definitions of Reachability to get a clear picture:

Upvotes: 9

Related Questions