javahibernatehashmapweak-referencesweakhashmap

WeakHashMap or HashMap?


So I have a chain of objects that reference each other from ORM / Hibernate

For some methods i need to be able to do some quick lookups for identifying keys.

So for that I currently have in all the objects that have Many to be able to do quick lookups of the Id's of the object in memory without having to fire off a gazillion database queries in the lifetime of the execution thread

HashMap<Integer,Country>     countriesTable
HashMap<Integer,State>       statesTable
HashMap<Integer,City>        citiesTable
HashMap<Integer,CityPart>    citypartsTable

But what i'm worried about is cyclic references being held and the objects never getting cleared by garbage collection because they all reference eachother through the ORM relations and they all have private maps pointing to eachohter

Now I have read about WeakHashMap that it will clear the references if there are no more strong references.

The question is Is it adviceable to use WeakHashMap in my situation or am I enough served by Hashmap and this setup and cyclic references will not impair my memory management.


Solution

  • If you have 3 objects that build an isle of isolation (A->B->C->A) and none of these is referenced from anywhere else, garbage collection can throw all of them away without problem.

    But a WeakHashMap will not help in your situation, as in a WeakHashMap only the keys are referenced weakly. (First sentence from WeakHashMap JavaDoc is "Hash table based implementation of the Map interface, with weak keys.") The values are still hard references. So a WeakHashMap will not help you in your case. If the Integer objects used as keys are not referenced from somewhere else, e. g. from within the objects it is even worse, as then they are eligible for garbage collection and thrown aways eventually.

    What you would need is a normal HashMap if your Integer objects are not referenced anywhere else, or a WeakHashMap if those objects are the ones referenced from within your objects but you also have to wrap the values in WeakReference instances and then when retrieving your objects from your map check whether they are still available or got garbage collected.