如果我將對象添加到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. 垃圾回收和cgo
- 2. Spidermonkey和垃圾回收
- 3. Objective-c和垃圾回收
- 4. 循環和垃圾回收
- 5. JDBC垃圾回收
- 6. Java:垃圾回收
- 7. C#垃圾回收
- 8. Java:垃圾回收
- 9. Erlang垃圾回收
- 10. java垃圾回收
- 11. Python垃圾回收
- 12. JS垃圾回收
- 13. Javascript垃圾回收
- 14. PhoneGap垃圾回收
- 15. java - 垃圾回收
- 16. 垃圾回收問題
- 17. Java垃圾回收5
- 18. asp.net垃圾回收通知
- 19. nodejs垃圾回收輸出
- 20. .Net 4垃圾回收
- 21. context.detach - 用於垃圾回收
- 22. 垃圾回收太慢
- 23. Python線程垃圾回收
- 24. 查找垃圾回收根
- 25. 每100秒垃圾回收
- 26. 垃圾回收Java類
- 27. Ruby/Rails垃圾回收
- 28. 強制垃圾回收
- 29. Javascript/ECMAScript垃圾回收
- 30. Perl XS垃圾回收
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