本文介绍了从地图存储条目安全吗?会导致内存泄漏吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了这段代码(适应虚拟数据):

I'm running into this code (adapted with dummy data):

public Map<String, Integer> queryDatabase() {
    final Map<String, Integer> map = new TreeMap<>();
    map.put("one", 1);
    map.put("two", 2);
    // ...
    return map;
}

public Map.Entry<String, Integer> getEntry(int n) {
    final Map<String, Integer> map = queryDatabase();
    for (final Map.Entry<String, Integer> entry : map.entrySet()) {
        if (entry.getValue().equals(n)) return entry; // dummy check
    }
    return null;
}

然后将Entry存储到一个新创建的对象中,该对象在未定义的时间段内保存到高速缓存中:

The Entry is then stored into a newly-created object that is saved into a cache for an undefined period:

class DataBundle {
    Map.Entry<String, Integer> entry;

    public void doAction() {
    this.entry = Application.getEntry(2);
    }
}

虽然在一分钟内多次调用queryDatabase,但是应在随后的gc循环中丢弃本地Maps.我有理由相信,DataBundle保留Entry引用会完全阻止收集Map.

While queryDatabase is called multiple times in a minute, the local Maps should be discarded at the consequent gc cycle. I have reason to believe though, that DataBundle keeping an Entry reference prevents the Map from being collected at all.

此外,java.util.TreeMap.Entry拥有对兄弟姐妹的多个引用:

Besides, a java.util.TreeMap.Entry holds multiple references to siblings:

static final class Entry<K,V> implements Map.Entry<K,V> {
    K key;
    V value;
    Entry<K,V> left;
    Entry<K,V> right;
    Entry<K,V> parent;
    // ...
}


问:Map.Entry存储到成员字段中是否会将本地Map实例保存到内存中?


Q: Does storing a Map.Entry into a member field retain the local Map instances into memory?

推荐答案

Map.Entry 在该区域没有做出任何承诺,因此您也不应做任何假设.

The contract for Map.Entry does not make any commitments in that area so you should not make any assumptions either.

由于这个原因,如果您希望存储从Map.Entry派生的Key-Value对,则应该进行复制.

For this reason, if you wish to store Key-Value pairs derived from a Map.Entry then you should take copies.

这篇关于从地图存储条目安全吗?会导致内存泄漏吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 17:26