我有一个控制台Java应用程序,它需要来自数据库的一些数据。由于应用程序每隔30秒持续运行一次,为了减轻数据库的压力,我使用了某种类型的缓存来存储数据。
因为数据库中没有大量需要的数据,所以我使用单例Hashmap作为缓存。我的缓存类如下所示:
public class Cache extends Hashmap<Integer, Hashmap<Integer, ArrayList<String>> {
//some code
}每隔5分钟,系统将通过以下方式刷新缓存:
1)对现有数据调用"clear()“;2)用来自数据库的新数据填充高速缓存。
告诉我,如果我为我拥有的结构调用" clear ()“(”嵌套的“哈希图),Java会清除我的缓存键下包含的所有数据,还是会导致内存泄漏?
发布于 2013-09-04 16:55:48
你可以这样做,但我建议一个更好的选择是替换它。如果你有多个线程,这会更有效率。
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;
}
}
}这既是线程安全的,也是影响最小的。
发布于 2013-09-04 17:01:28
这篇文章对你有帮助。
Is Java HashMap.clear() and remove() memory effective?
而且,HassMap不是线程安全的。如果你想使用单例HashMap,你最好使用ConcurrentHashMap。
https://stackoverflow.com/questions/18609169
复制相似问题