Re: more on SoftReference, WeakReference and PhantomReference
"Harold Meder" <[email protected]>
| Newsgroups | gmane.org.user-groups.trijug.juglist |
|---|---|
| Message-ID | <000401c61f15$2f4604d0$6402a8c0@Rose2> |
Yes. It appears that when you return from a method, its stack is garbage collected. That suggests to me that when ever you have a service provided by a thread in an infinite loop, it is wise to call a method from within the loop to do the work. That way, all the resources you that you freed up after completing the work will be garbage collected on completion of your work. If you don't do this, you might find that garbage collection only happens as you are trying to get work done on the next time around the loop as strong references on your stack are overwritten. Harold Meder. -----Original Message----- From: [email protected] [mailto:[email protected]] On Behalf Of Richard O. Hammer Sent: Saturday, January 21, 2006 7:31 PM To: Research Triangle Java User's Group mailing list. Subject: Re: [Juglist] more on SoftReference,WeakReference and PhantomReference Concerning the meaning of "scope" as used by the garbage collector -- I have assumed that a referent object fell out of scope when either: 1. the object in which the referent object is an instance variable is no longer reachable, or 2. the method in which the referent object is a local variable has finished. In your example you use another valid but different meaning of falling out of scope: 3. the block of code in which a local variable is declared has finished, although the same method is still being executed. Below I show another test, following your model, which seems to confirm that the garbage collector uses at least definition 2 above. The append code produces the following output. ----------- Both Weak References survive before call to gc() 111, 222 Neither Weak Reference survives call to gc() null, null ----------- import java.lang.ref.WeakReference; public class RefTest { public static void main (String[] args) { WeakReference <Integer> wr1 = getWeakReference(111); WeakReference <Integer> wr2 = getWeakReference(222); System.out.println ( "Both Weak References survive before call to gc()\n" + wr1.get () + ", " + wr2.get ()); System.gc (); System.out.println ( "Neither Weak Reference survives call to gc()\n" + wr1.get () + ", " + wr2.get ()); } static WeakReference<Integer> getWeakReference(int i) { Integer obj = new Integer(i); return new WeakReference <Integer> (obj); } }