Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

WeakReferences and garbage collector...

Status
Not open for further replies.

DoraC

Programmer
May 7, 2002
98
0
0
US
Hi,

Is there any way to have the garbage collector remove not only the referent contained by a WeakReference (if the w.r. contains the only reference to the referent), but the WeakReference object itself?

I need to use a "WeakSet", and I've attempted to simulate one by loading a HashSet with WeakReferences to objects. This works fine, except it starts to fill up with empty WeakReference objects!! (once their referents have been garbage-collected).

I suppose I could use a WeakHashMap, but I don't like the idea of never using the value portion of the map. It seems strange to me that the garbage collector doesn't also remove W.R.'s, and that there appears to be no implementation of a "WeakSet" outside of a value-free WeakHashmap. That's what I'll wind up using if nothing better exists, but I would think something should..? perhaps?

thank you..!
dora
 
Well, how can the GC remove the WeakReferences when the hashset still has strong references to them? This violates the invariant that the GC must obey that any object that is strongly reachable can never be garbage collected.

What you are looking for can be resolved by using the ReferenceQueue class. When the garbage collector gc's the referrent for a WeakReference, the reference is placed on the queue with which the reference was registered when it was created. When you find a reference in the queue, you can remove it from your set and then it will be gc'd as well.

If you want details on how this works, I'd suggest you poke through the source code for the WeakHashMap.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top