Results 1 to 2 of 2
  1. #1
    j2me64's Avatar
    j2me64 is offline Senior Member
    Join Date
    Sep 2009
    Location
    Zurich, Switzerland
    Posts
    962
    Rep Power
    6

    Default how many objects are eligible for gc?

    i'm just preparing for the scjp and i got some understanding problems with the following code

    Java Code:
    /**
     * @author j2me64
     * Question 11 p. 284 out of Book SCJP
     */
    
    class Beta {}
    
    class Alpha {
    	static Beta b1;
    	Beta b2;
    }
    
    public class Tester {
    
    	public static void main(String[] args) {
    		Beta b1 = new Beta();
    		Beta b2 = new Beta();
    		Alpha a1 = new Alpha();
    		Alpha a2 = new Alpha();
    		
    		a1.b1 = b1;
    		a1.b2 = b1;
    		a2.b2 = b2;
    		
    		a1 = null;
    		b1 = null;
    		b2 = null;
                    // do stuff
    	}
    }

    the question is: When line 16 (// do stuff) is reached, how many objects will be eligible for garbage collection?

    the right answer is 1. but for me it's not very clear which object is eligible and why there are not more then 1 eligible objects. i think it has to do with the static Beta b1 in the class Alpha. it would be great if somebody can give an explanation.

  2. #2
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,458
    Rep Power
    20

    Default

    I'd say that the Alpha object previously referenced by the variable a1 is the only object eligible for GC.

    -- a2 isn't nulled
    -- b1 being static is referenced from the Alpha class and remains referenced as long as the class is loaded
    -- b2 is referenced from a2

    It's bad form to access a static member via an instance variable.
    Java Code:
    a1.b1 = b1;
    should be
    Java Code:
    Alpha.b1 = b1;
    I suppose it's allowed for trick questions ;-\

    db

    db

Similar Threads

  1. How to map 2 different objects together?
    By einnhann in forum New To Java
    Replies: 5
    Last Post: 12-22-2009, 10:42 AM
  2. Objects
    By Silverlining in forum New To Java
    Replies: 3
    Last Post: 11-11-2009, 03:36 PM
  3. Replies: 1
    Last Post: 01-22-2009, 05:25 PM
  4. 1 to 1 Objects
    By this.that in forum New To Java
    Replies: 4
    Last Post: 08-07-2008, 11:09 PM
  5. how many objects ?
    By kevinsong in forum Advanced Java
    Replies: 16
    Last Post: 07-16-2008, 06:59 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •