|
![]() |
In object oriented systems, most objects are created, used and then "thrown away". For these, you use regular references. There are a few cases where your system might hold onto an object for a long time and not throw it away. Here, you need to give some hints to the garbage collector about your intent. Monica Pawlan from JavaSoft wrote a good article on the new "Reference Objects" feature of Java 2. I got the basic idea (more fine control over garbage collection behavior for caches, among other things) but the finer points of the 3 types escaped me. So I decided to read everything I could, write some sample code, and see if I could crisply define what the different references objects mean. I think that the best way to express what the reference objects mean is to imagine a conversation between a developer and the virtual machine's garbage collector: Regular reference: "Keep this object around even if it causes the VM to run out of memory and exit. I can't live without it." java.lang.ref.SoftReference: "try to keep this object around if you have some free memory; I can handle it if the object disappears on me but it would be better to keep it around." java.lang.ref.WeakReference: "don't keep this object around just for me, I only need to be able to get to it as long as it's strongly or softly reachable (by somebody else). Once it's just weakly reachable, you should get rid of it." java.lang.ref.PhantomReference: "I just want to know when this object has been finalized, so that I can do some stuff in response [probably in JNI land]. I'll call remove() on its java.lang.ref.ReferenceQueue and wait for that to return, then I'll do my thing and be sure to call clear() so the phantomly reachable object can be reclaimed." java.lang.ref.ReferenceQueue: "I need to know when this Reference object is of the same strength as the strongest Reference to the referent [if it's a WeakReference, then the referent is weakly reachable] so that I can do something about it. I'll call poll or remove and do my thing if I get a positive response. I might even decide to clear the reference object's reference so that the referent can be garbage collected." Unfortunately, in the process of writing some test classes to explore reference objects, I determined that the GC behavior is somewhat difficult to make deterministic, especially because the specification allows for some flexibility in implementation - so I didn't really prove that much. Still, here's what I wrote. (The superGC() method came from an article, I didn't write that part.) |