Reputation: 553
Is it possible to see how many references there are currently to an Object?
Situation
I have instances of Map.Entry
stored in references other than their Map
, so I can keep them where I need them and directly access the values without constantly checking for the mapping to its key.
I want the references to be updated to changed to the Map
. They won't if I use Map.get(key)
.
There are problems with that however...
If an Entry
is removed, it could still exist in references which would still return the value. Though, I could choose to never remove, but set them to null
, to overcome that.
However, I'm worried the above would cause the memory to be filled with a huge amount of null
entries over time, should there be a lot of temporary unique keys used, like dates.
I figured if there was a way to get the amount of references to a Map.Entry
with the value null
, if it'd be 1
, then that would be the one in the Map
, meaning there are no other references, so it's safe to remove the Entry
. And otherwise, if there are other references, it should remain and still return null
.
Is there such possibility?
Upvotes: 1
Views: 157
Reputation: 60997
Java memory management does not work that way. Nothing is keeping track of the number of references to an object.
It sounds like your real problem is that you don't have a good model of the lifecycle of your objects. If something is retrieving Map.Entry
objects and holding on to the references beyond when they would otherwise have been collected, then that's where the leak lies. You should probably use a memory profiler (I've found YourKit useful for this purpose, but there are others) to determine what is filling up memory.
They're about C#, not Java, but the points in these blog posts apply to your situation as well:
Upvotes: 2