简体   繁体   English

循环GC是否可以在地图中使用?

[英]Does circular GC work in a map?

I have a User object which strongly refers to a Data object. 我有一个User对象,该对象强烈引用Data对象。

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. 如果我使用弱键创建Map<Data, User> (使用Guava MapMaker ),则只有在其他任何地方均未引用该键时,才会删除该键。 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, ie never, unless the GC's circular reference detection also works when crossing a map (I hope you understand what I mean :P) 但是,它始终由其映射到的User对象引用,而该对象仅在删除Data键时才从地图中删除,即从不删除,除非在穿越地图时GC的循环参考检测也起作用(我希望你明白我的意思:P)

Will User s+ Data s be garbage collected if they're no longer used elsewhere in the application, or do I need to specify weak values as well? 如果User s + Data不再在应用程序中的其他地方使用,是否会被垃圾回收,还是我还需要指定弱值?

The GC doesn't detect circular references because it doesn't need to. GC不会检测循环引用,因为它不需要。

The approach it takes is to keep all the objects which are strongly referenced from root nodes eg 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 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. 引用计数通常用于解释一种垃圾收集,但似乎未在任何JVM实现中使用它。

This is an interesting link http://www.ibm.com/developerworks/library/j-jtp10283/ 这是一个有趣的链接http://www.ibm.com/developerworks/library/j-jtp10283/

In documentation you see: weakKeys() Specifies that each key (not value) stored in the map should be wrapped in a WeakReference (by default, strong references are used). 在文档中,您将看到:weakKeys()指定应将映射中存储的每个键(非值)都包装在WeakReference中(默认情况下,使用强引用)。

since it is weakReferenced it will be collected. 由于它是弱引用,它将被收集。

http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/collect/MapMaker.html http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/collect/MapMaker.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM