1

Is it possible for the finalize() method of an Object to be called despite the Object being present within a List or Map. If not, how would it be possible to detect when an Object is no longer accessible by anything except only having a presence in the List/Map.

The reason behind this is that I have a map which has a key of UUID which is the unique ID for the Object's as the Map's value. I need to know when the "value" objects of the map are no longer accessible so I can clear space as there will be a lot of objects, but I also need to have them within the map until they are no longer accessible anywhere else so I can retrieve them via their UUID when required.

Any help is much appreciated, thanks!

C_Neth
  • 696
  • 2
  • 9
  • 23

1 Answers1

2

Well, first of all if you have

Map<K,V> map = new HashMap<>();
map.put(key,value);

and map is still referenced, then value is still referenced (via the map). So it won't get garbage collected.

If you want for value to be garbage collected you might want to consider reading about WeakReference What is the difference between a soft reference and a weak reference in Java?;

This way you can have

Map<K,WeakReference<V>> map = ...
map.put(key, new WeakReference<V>(v));

This way you can get the value using its UUID, simply by map.get(key), but the value can also be garbage collected, and you can check if it has by

if (map.get(key).get()==null){
   //object was garbage collected
}

However, notice that if your value object is still referenced from another reference, it won't be garbage collected. So hope this help.

If your purpose is to implement a cache that makes sure that you don't use to much information, you might want to look at Guava's cache. Which has a memory bound, if you want or/and expiration time for objects. http://www.baeldung.com/guava-cache

Community
  • 1
  • 1
user967710
  • 1,815
  • 3
  • 32
  • 58