Java 哈希映射和内存泄漏
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18609169/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java hashmaps and memory leaks
提问by guest86
I have a console Java application that needs some data from the database. As the application is running constantly, every 30 seconds, in order to lower the strain on the DB i'm using some sort of cache for the data.
我有一个控制台 Java 应用程序,它需要来自数据库的一些数据。由于应用程序每 30 秒持续运行一次,为了降低数据库的压力,我使用某种缓存来存储数据。
Because there isn't a large amount of the needed data in the database, i'm using singleton Hashmap as my cache. My cache class looks like this:
因为数据库中没有大量所需的数据,所以我使用单例 Hashmap 作为我的缓存。我的缓存类如下所示:
public class Cache extends Hashmap<Integer, Hashmap<Integer, ArrayList<String>> {
//some code
}
Every 5 minutes system will refresh the cache by:
每 5 分钟系统将通过以下方式刷新缓存:
1) calling "clear()" for the existing data 2) filling the cache with new data from the db.
1) 为现有数据调用“clear()” 2) 用来自数据库的新数据填充缓存。
Tell me, if i call the "clear()" for the structure i have ("nested" hashmaps) will Java clear all the data containd under my cache keys, or i'll end up with memory leaks?
告诉我,如果我为我拥有的结构(“嵌套”哈希图)调用“clear()”,Java 会清除缓存键下包含的所有数据,还是会导致内存泄漏?
采纳答案by Peter Lawrey
You can do this, but I suggest a better alternative is to replace it. This will be more efficient if you have multiple threads.
您可以这样做,但我建议更好的替代方法是更换它。如果您有多个线程,这将更有效。
public class Cache {
private Map<Integer, Map<Integer, List<String>>> map;
public Cache(args) {
}
public synchronized Map<Integer, Map<Integer, List<String>>> getMap() {
return map;
}
// called by a thread every 30 seconds.
public void updateCache() {
Map<Integer, Map<Integer, List<String>>> newMap = ...
// build new map, can take seconds.
// quickly swap in the new map.
synchronzied(this) {
map = newMap;
}
}
}
This is both thread safe and has a minimum of impact.
这既是线程安全的,又具有最小的影响。
回答by Dohyun Jung
This article is helpful for you.
这篇文章对你有帮助。
Is Java HashMap.clear() and remove() memory effective?
Java HashMap.clear() 和 remove() 内存有效吗?
And, HassMap is not thread safe. If you want using singleton HashMap, You had better use ConcurrentHashMap.
而且,HassMap 不是线程安全的。如果要使用单例 HashMap,最好使用 ConcurrentHashMap。