I want to keep a map of singleton objects based on their ID, just to ensure that everyone gets the same copy. The creation of these objects happens seldom, and I don't want or need the overhead of a concurrent map (which will internally keep essentially multiple maps in memory). But I do need the map to support weak keys, so that when nobody is using a particular instance the record will be dropped from the map.
So what choice do I have? Guava MapMaker
and CacheBuilder
create concurrent maps, which use a lot more memory than I need. I don't need "concurrency" --- I just need thread safety. Yes, I could set the concurrency level to 1
, but according to the API documentation this is is only a hint, and may be ignored altogether in the future.
I could use Java Collections to create a simple synchronized HashMap
and use putIfAbsent(...)
, but that doesn't give me the benefit of weak values. I could store weak references, but they wouldn't automatically be expunged on access of the map.
If I had a version of Java's WeakHashMap
that supported weak values instead of weak keys, I could wrap it in a synchronized map and be done with it.
I believe that long ago Apache Commons Collections had a map builder that allowed the specification of weak values, but we're using Guava instead.
Any suggestions? And please, read the full question before jumping to throw in a suggestion I've already mentioned.