I guess I'm another person trying to make some kind of a cache with WeakHashMap. And I need some help with it.
I have bunch of TrackData
objects that contain information about audio tracks. Then there are Track
objects that keep reference to the TrackData
inside. Several tracks can point to the same TrackData
. Then I have TrackDataCache
class that looks like this:
public class TrackDataCache {
private static TrackDataCache instance = new TrackDataCache();
public static TrackDataCache getInstance() {
return instance;
}
private WeakHashMap<TrackData, WeakReference<TrackData>> cache = new WeakHashMap<TrackData, WeakReference<TrackData>>();
public void cache(Track track) {
TrackData key = track.getTrackData();
WeakReference<TrackData> trackData = cache.get(key);
if (trackData == null) {
cache.put(key, new WeakReference<TrackData>(key));
} else {
track.setTrackData(trackData.get());
}
}
}
So when I load a track, I call TrackDataCache.cache()
and if its track data was not loaded before, it is cached or replaced with cached copy otherwise (TrackData
overrides equals() method to check for location and subsong index). I want to use weak references so that I don't need to care when I remove Tracks.
I wanted to ask if it is an ok practice to keep weak reference to the key in WeakHashMap, and if not, how should I approach this problem? I need weak references and constant time retrieving of cached values. I was thinking of copying WeakHashMap code and making getEntry()
method public, which solves the problem but it's such a bad hack :(
PS. I understand that either apache or google collections may have something like this, but I really don't want to add 2Mb dependencies.