3

我有一个控制台 Java 应用程序,它需要数据库中的一些数据。由于应用程序不断运行,每 30 秒一次,为了降低数据库的压力,我正在使用某种数据缓存。

因为数据库中没有大量需要的数据,所以我使用单例 Hashmap 作为我的缓存。我的缓存类如下所示:

public class Cache extends Hashmap<Integer, Hashmap<Integer, ArrayList<String>> {
//some code
}

每 5 分钟系统将通过以下方式刷新缓存:

1)为现有数据调用“clear()” 2)用数据库中的新数据填充缓存。

告诉我,如果我为我拥有的结构(“嵌套”哈希图)调用“clear()”,Java 会清除我的缓存键下包含的所有数据,还是会导致内存泄漏?

4

2 回答 2

2

你可以这样做,但我建议更好的选择是替换它。如果您有多个线程,这将更有效率。

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-04T08:55:48.070 回答
0

这篇文章对你很有帮助。

Java HashMap.clear() 和 remove() 内存有效吗?

而且,HassMap 不是线程安全的。如果你想使用单例HashMap,你最好使用ConcurrentHashMap。

于 2013-09-04T09:01:27.980 回答