2

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

  • Continent
    • has many countries
    • has many states
    • has many cities
    • has many cityparts
  • Country
    • has one Country
    • has many states
    • has many cities
    • has many cityparts
  • State
    • has one Continent
    • has one Country
    • has many cities
    • has many cityparts
  • City
    • has one Continent
    • has one Country
    • has one State
    • has many cityparts
  • City part
    • has one Continent
    • has one Country
    • has one State
    • has one City

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.

4

1 回答 1

3

如果您有 3 个对象构建了一个隔离岛A->B->C->A

但是 aWeakHashMap在您的情况下无济于事,因为在 aWeakHashMap只有键被弱引用。(WeakHashMapJavaDoc 中的第一句话是“Map 接口的基于哈希表的实现,带有弱键。”)这些值仍然是硬引用。所以WeakHashMap在你的情况下 a 不会帮助你。如果用作键的整数对象没有从其他地方引用,例如从对象内部,那就更糟了,因为它们有资格进行垃圾收集并最终被丢弃。

HashMap如果您的 Integer 对象未在其他任何地方引用,或者WeakHashMap如果这些对象是从您的对象中引用的对象,那么您需要的是正常的,但您还必须将值包装在WeakReference实例中,然后在从地图中检索对象时检查它们是否仍然可用或被垃圾收集。

于 2016-04-12T13:32:21.223 回答