• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Garbage Collection

 
Max Campa
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi there,

can anyone explain to me the following:

Given:


When line 20 is reached, how many objects will be eligble for garbage collection?

The correct answer is 1 and the explanation is:

It should be clear that there is still a reference to the object referred to by a2 ( I understand that), and that there is still a reference to the object referred to by a2.b2 ( I understand that).

What might be less clear is that you can still access the other Beta object trough the static variable a2.b1 becausae it s static ( I dont understand this).

Which object is elegible for GC?

Regards

Max
 
Deepak Bala
Bartender
Posts: 6663
5
Firefox Browser Linux MyEclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is hard to read code that is not inside the CODE tags. Can you please edit your post and put your code inside these tags ?
 
George Coolidge
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The reason is even though

looks like that an instance variable is assigned, it is actually assigning a class variable, aka, static variable. So b1 is still referenced in Alpha.b1, remember, even though a2 gets collected, b1 still won't be collected since you don't need to instantiate an instance to assign a class variable.

So only a1 is not referenced by anybody and becomes dangling reference, and therefore only 1 object will be garbage collected. In real code, the form in

is discouraged since it is confusing to the readers and sometimes coders themselves.
 
Max Campa
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you George. I have debugged the code and now it makes sense.
 
George Coolidge
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are always welcome.
Max Campa wrote:Thank you George. I have debugged the code and now it makes sense.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic