Reference Queue Tip
I have a memory leak I was tracking down in a java application, so I thought it would be good to track allocations and try to figure out if they were ever getting released. The thing that seemed to be running me out of memory was an object that had a couple of small fields and a giant byte array. The fields other than the byte array were mostly redundant, so I removed most of them, and just moved this byte array around where I needed it.
Now, I just needed to make sure I wasn't holding on to a reference to this byte array longer than necessary. To accomplish that, I created a small class to which all of these byte arrays were allocated so it could wrap them in WeakReferences
and ensure they go away on their own. For each byte array that was allocated, I'd wrap it in a custom subclass of WeakReference
and stick it in my ReferenceQueue
. I had a recurring job scheduled to check for things coming back out of the queue and counting up the number of items and number of bytes removed.
I saw many references created, but I never saw a single one come back out of the queue. I also didn't see my memory usage growing in any way that could correlate to the way in which I was dumping byte arrays into my application.
I can't find any documentation about this behavior, but my theory is the WeakReference
itself was getting GCd' before the byte array, preventing it from enqueueing itself into the ReferenceQueue
.
By maintaining a strong reference to the WeakReference
, it's able to do its job properly and I can make sense of what big objects are going in and out of my VM.