• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Garbage Collection - Sequence of events

 
Thomas Hauck
Ranch Hand
Posts: 95
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the following code, after which statement (earliest), will the object originally held in 's' be eligible for garbage collection ?


Select 1 Option

a. It will not be Garbage Collected till the end of the program.
b. Line 5
c. Line 6
d. Line 7
e. Line 10
-------

Answer: c
Explanation:
Since there is only one reference to Student object, as soon as it is set to null, the object held by the reference is eligible for GC, here it is done at line 6.
Note that although an object is created at line 7 with the same parameters, it is a different object and it will be eligible for GC after line 10.
________________________________________________________

The question asks, after which statement (earliest), will the object originally held in 's' be eligible for garbage collection ?
The way I should interpret this statement is ,
as soon as the reference variable 's' is set to null, it becomes eligible for garbage collection.



Sequence of Events:

1) Reference variable 's' is set to null on line 6
2) Reference variable 's' (which created the original object on line 3) is now eligible for garbage collection
3) On line 7 the same reference variable 's' is used again to create a new object.
(This is a new object and the previous object, which has had its reference variable set to null is now eligible for garbage collection,
since we do not know when the JVM is going to collect the object pointed to by the reference variable 's' .)

Please confirm.
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 35274
384
Eclipse IDE Java VI Editor
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Correct. It may be garbage collected at line 6 or 7 or 8 or ...

That's why the question asks about the earliest.
 
Roel De Nijs
Sheriff
Posts: 10662
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your analysis is correct! There are no guarantees whatsoever when GC will run. Even calling System.gc() in your code will not guarantee GC will run. It's nothing more but a friendly request: "Dear JVM, could you pretty please run garbage collection". The JVM can decide to honour your request or simply ignore it.

Just a little remark: if you post a (little) code snippet, put this code snippet into code-tags. It improves the readibility of your post and that way you are more likely to get an answer. I added the code-tags for you this time. Looks good, doesn't it?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic