gpt4 book ai didi

java - GC 不会从weakhashmap 中删除对象

转载 作者:行者123 更新时间:2023-12-02 09:08:40 24 4
gpt4 key购买 nike

我有一个测试应用程序,其中有一个类存储 map 和一个调用该类方法的按钮:

Map<Object, Object> weakMap = new WeakHashMap<Object, Object>();

该按钮执行以下操作:

public void fillWeakHashMap(int size) {
List<String> createObjects = (List<String>) createObject(size);
for (Object ob : createObjects) {
weakMap.put(ob, ob);
}
}

因此,带有 map 的主类存在,但我放入其中的对象是在单独的方法中创建的,并且由于它是一个 WeakHashMap 我认为从该方法退出后 fillWeakHashMap code>map中的键/对象将被GC清除。

我打开 VisualVM->VisualGC 并单击 Monitor->PerformGC 10 次,旧空间几乎已满,这意味着 GC 没有清除这些对象。那么我做错了什么?

最佳答案

WeakHashMap的javadoc第一句says :

Hash table based implementation of the Map interface, with weak keys. An entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use. More precisely, the presence of a mapping for a given key will not prevent the key from being discarded by the garbage collector, that is, made finalizable, finalized, and then reclaimed. When a key has been discarded its entry is effectively removed from the map, so this class behaves somewhat differently from other Map implementations.

再往下写:

The value objects in a WeakHashMap are held by ordinary strong references. Thus care should be taken to ensure that value objects do not strongly refer to their own keys, either directly or indirectly, since that will prevent the keys from being discarded.

也就是说,只有键是弱引用,而值是强引用。在您的代码中,每个键也使用一个值,因此被强引用,因此不会被垃圾回收。

关于java - GC 不会从weakhashmap 中删除对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30003937/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com