Eslam Hamdy
Eslam Hamdy

Reputation: 7396

garbage collector Issue

this question is like my previous one Given:

3. interface Animal { void makeNoise(); }
4. class Horse implements Animal {
5.   Long weight = 1200L;
6.   public void makeNoise() { System.out.println("whinny"); }
7.  }
8.  public class Icelandic extends Horse {
9.   public void makeNoise() { System.out.println("vinny"); }
10.  public static void main(String[] args) {
11.    Icelandic i1 = new Icelandic();
12.    Icelandic i2 = new Icelandic();
13.    Icelandic i3 = new Icelandic();
14.    i3 = i1; i1 = i2; i2 = null; i3 = i1;
15.  }
16. }

When line 14 is reached, how many objects are eligible for the garbage collector?

A. 0

B. 1

C. 2

D. 3

E. 4

F. 6

I chose A but the right answer is E, but I don't know Why?

Upvotes: 2

Views: 4638

Answers (2)

Tugrul Ates
Tugrul Ates

Reputation: 9687

Let's call the three Icelandic objects created in main as A, B and C.

Initialy

  • i1=A, i2=B and i3=C;

After i3 = i1

  • i1=A, i2=B and i3=A;

After i1 = i2

  • i1=B, i2=B and i3=A;

After i2 = null:

  • i1=B, i2=null and i3=A;

After i3 = i1

  • i1=B, i2=null and i3=B

In line 14, there are standing references to only B object of type Icelandic. A and C are lost in the running program.

Each Icelandic object that is lost gives garbage collector two objects to collect, ie. the Icelandic object itself and the Long object within every Icelandic, which make the total number of garbage collected objects 4.

Since makeNoise methods are never called, they do not change the outcome.

Upvotes: 8

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340923

If you look closely, after all assignments in the end i1 and i3 point to the second object while i2 points to null. This means two Icelandic objects are eligible for GC.

Each Icelandic object contains one Long which makes 4 objects eligible for GC in total. Interestingly if the constant was 12L, the answer would be: 2 due to Long internal constant cache. Also note that "whinny" and "vinny" are from the constant pool and won't be garbage collected.

Once you leave the scope where all i1, i2 and i3 are declared, remaining two objects are eligible for GC as well.

Upvotes: 2

Related Questions