Search code examples
javagarbage-collectionweak-references

Does circular GC work in a map?


I have a User object which strongly refers to a Data object.

If I create a Map<Data, User> (with Guava MapMaker) with weak keys, such a key would only be removed if it's not referenced anywhere else. However, it is always refered to by the User object that it maps to, which is in turn only removed from the map when the Data key is removed, i.e. never, unless the GC's circular reference detection also works when crossing a map (I hope you understand what I mean :P)

Will Users+Datas be garbage collected if they're no longer used elsewhere in the application, or do I need to specify weak values as well?


Solution

  • The GC doesn't detect circular references because it doesn't need to.

    The approach it takes is to keep all the objects which are strongly referenced from root nodes e.g. Thread stacks. This way objects not accessible strongly (with circular references or not) are collected.

    EDIT: This may help explain the "myth"

    http://www.javacoffeebreak.com/articles/thinkinginjava/abitaboutgarbagecollection.html

    Reference counting is commonly used to explain one kind of garbage collection but it doesn't seem to be used in any JVM implementations.

    This is an interesting link http://www.ibm.com/developerworks/library/j-jtp10283/