Eslam Hamdy
Eslam Hamdy

Reputation: 7396

count number of objects that's eligible for GC

Good Evening, please look at this code samples that demonstrates the number of objects that's eligible for GC:

public class CardBoard {

Short story = 5;

CardBoard go(CardBoard cb) {
    cb = null;
    return cb;
}

public static void main(String[] args) {
    CardBoard c1 = new CardBoard();
    CardBoard c2 = new CardBoard();
    CardBoard c3 = c1.go(c2);
    c1 = null;
   // do Stuff

   }
}

i see that there's four objects that's eligible for GC when do Stuff is reached that's c3 and it's associated story object and c1 and it's associated story object, what do you see?

Upvotes: 2

Views: 482

Answers (1)

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340883

There is exactly 1 object eligible for GC - the one previously referenced by c1. c3 points to null (CardBoard.go() always returns null).

Also remember that c1 and c2 variables are only references, not objects. Thus they don't need to be garbage collected. They live on stack, not on heap.

Finally don't be fooled by:

CardBoard go(CardBoard cb) {
  cb = null;
  return cb;
}

this only nullifies cb reference (parameter), not c2 reference.


Short story = 5;

is a separate gotcha. If it was short story then it wouldn't count as a separate object. But Short is an object, so technically CardBoard points to another object eligible for GC. However! Due to primitive wrappers caching 5 is actually part of Short static cache and is never really eligible for GC. In other words object of type Short representing 5 is always referenced by static cache in Short.

Here comes the best part. If it was:

Short story = 5000;

then the answer would be... 2. That's because Short.valueOf((short)5000) always returns new instance of Short (eligible for GC) while Short.valueOf(5) always returns the same one.

Wow, that was tricky!

Upvotes: 8

Related Questions