Solved

# Garbage Collection in Java, Could you please make corrections for my HEAP/STACK diagram?

Posted on 2011-02-26

This is a question about garbage collection. I want to construct a HEAP/STACK diagram for the code given below to determine the number of Objects created, and number of Objects eligible for garbage collection.

I have already drawn the HEAP/STACK diagram, which is still incomplete. The locations assigned for each objects are randomly given e.g. 100,200,300.

1. When the line “//do stuff” is reached, how many objects will be eligible for garbage

collections? This correct answer is only one object is eligible but I need to know why?

2. Could you please make corrections for the HEAP/STACK diagram I constructed so that I could

get the correct answer?

3. I am stuck with “static Beta b1”, since I am not use how to use static reference variable in the

HEAP/STACK diagram.

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 Incomplete HEAP/STACK Diagram:

HEAP

100: Beta referenceBy b1

200: Beta referenceBy b2

300: Alpha referenceBy a1

400: BetaObject referenceBy 300

500: Alpha referenceBy a2

600: BetaObject referenceBy 500

STACK

b1 : 100

b2 : 200

a1 : 300

a2 : 500

Could you please make corrections to my diagram above, so that I could determine the number of objects eligible for Garbage Collection?

Thank you in advance :)