Reputation: 2956
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.
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:
public class Cache extends Hashmap<Integer, Hashmap<Integer, ArrayList<String>> {
//some code
}
Every 5 minutes system will refresh the cache by:
1) calling "clear()" for the existing data 2) filling the cache with new data from the db.
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?
Upvotes: 3
Views: 16079
Reputation: 533880
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.
Upvotes: 2
Reputation: 11
This article is helpful for you.
Is Java HashMap.clear() and remove() memory effective?
And, HassMap is not thread safe. If you want using singleton HashMap, You had better use ConcurrentHashMap.
Upvotes: 1