如果我将对象添加到HashMap
,然后在不再需要时调用remove
方法,它是否保证它们释放的资源将被释放(因为没有其他引用)?HashMap.remove和垃圾回收
回答
不,您可能从别的地方引用了该对象。
简单的例子:
Map < int, Object > map = new HashMap < int, Object >();
CustomObject x = new CustomObject();
map.put(1, x);
map.remove(1);
//you still have access to x
他的意思是...'map.put(x); x = null; map.remove(x);' – 2015-04-02 10:11:50
@JordiCastilla 'map.remove(x)'其中'x == null'不会按预期工作。 – 2015-04-02 10:12:58
@GoogleHireMe他的意思是map.put(key,x); X = NULL; map.remove(键); – olegst 2015-04-02 10:17:16
如果Map是唯一一个引用Object的对象,并且您从Map中删除了Object引用,那么是的,这个Object不再被任何引用,并且有资格使用GC。一如既往,它所花费的资源将保证被释放,但不能保证何时会发生。
垃圾回收总是在所有对象初始化的堆内存中完成。当您在HashMap
中调用remove
方法时,它只会从中删除id和值,而不是您创建的对象。
HashMap
条目存储在一个数组中。如果删除一个条目,相关数组的位置将为null
。因此,hashMap
已不再提及已删除的value
对象。
然后垃圾回收的正常规则将应用于value
对象。
验证的简单代码。
public class REPL7 {
public static void main(String[] args) throws Exception {
Map<String, Foo> map = new HashMap();
map.put("one", new Foo("foo one"));
map.put("two", new Foo("foo two"));
// make the backing array accessible
Field field = map.getClass().getDeclaredField("table");
field.setAccessible(true);
Object[] obj = (Object[]) field.get(map);
// two references to Foo objects will be shown
System.out.println("obj = " + Arrays.toString(obj));
map.remove("one");
// only one reference to a Foo object will eb shown
System.out.println("obj = " + Arrays.toString(obj));
}
}
class Foo {
String marker;
Foo(String marker) {
this.marker = marker;
}
@Override
public String toString() {
return "Foo{" + marker + '}';
}
}
- 1. Hashmap.remove()被调用后立即发生垃圾回收吗?
- 2. Spidermonkey和垃圾回收
- 3. c#和垃圾回收
- 4. 垃圾收集和回调
- 5. HBase MemStore和垃圾回收
- 6. Objective-c和垃圾回收
- 7. 循环和垃圾回收
- 8. 垃圾回收和cgo
- 9. java垃圾回收
- 10. Java:垃圾回收
- 11. Python垃圾回收
- 12. C#垃圾回收
- 13. Erlang垃圾回收
- 14. java - 垃圾回收
- 15. JDBC垃圾回收
- 16. JS垃圾回收
- 17. requestAnimationFrame垃圾回收
- 18. vb.net垃圾回收
- 19. ColdFusion垃圾回收
- 20. PhoneGap垃圾回收
- 21. Chrome垃圾回收
- 22. Java:垃圾回收
- 23. Javascript垃圾回收
- 24. Parallel Copy垃圾回收器和Parallel Scavenge垃圾回收器的区别
- 25. 回收垃圾回收问题
- 26. 垃圾回收无法回收BitmapImage?
- 27. 删除根垃圾回收
- 28. AIR for iOS垃圾回收
- 29. Java垃圾回收器
- 30. Rebol&Red垃圾回收
HashMaps不存储对象。他们可以存储参考。 – immibis 2015-04-02 10:05:18
而不是'HashMap',你可以使用'WeakHashMap'。 – Prashant 2015-04-02 10:05:34
如果您从Map中删除的任何对象有任何过时的引用,那么它将无法启动GC。您需要在删除之前将其设置为空。 – Prashant 2015-04-02 10:13:30