• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Tim Cooke
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Devaka Cooray
  • Ron McLeod
  • paul wheaton
Saloon Keepers:
  • Tim Moores
  • Piet Souris
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Frits Walraven
  • Scott Selikoff

Garbage Collection doubt from www.danchisholm.net

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi friends,

Can you please help me with this question

class B {
private String name;
public B(String name) {this.name = name;}
public String toString() {return name;}
protected void finalize() {System.out.print(name);}
}
class H {
static B ba = new B("Ba");
static int i = 1;
static B m1(B b) {return b = new B("B" + i++);}
public static void main (String[] args) {
B x = m1(ba); m1(x);
System.out.println(", " + ba + ", " + x);
}}

Which of the following could be a result of attempting to compile and run the program?
a. Ba, B1, B2
b. B1, Ba, B2
c. , Ba, B1
d. B2, Ba, B1
e. BaB1b2, null, null
f. B1B2, ba, null


Correct answer is C and D, i.e , Ba, B1 B2, Ba, B1
The author assumes that the Garbage collector runs after m1(x) returns, even if it runs why does the gc collect the object in the order B2, Ba, B1 ? AS far as i know order cannot be guaranteed. so after ,Ba, B1, any of the options a,b,d can occur...

Can you please reply if my understanding is correct.
You can find the question(Q9) here http://www.danchisholm.net/oct1/mybook/chapter16/exam1.html
and the answers here http://www.danchisholm.net/oct1/mybook/chapter16/exam1ans.html

Thanks and regards,
Srikanth
 
Ranch Hand
Posts: 1032
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Welcome to the ranch!

The GC will never garbage collect ba or x. It might possibly collect the B object created during the invocation of m1(x), and that object has an String attribute name with the value "B2".

The possible outputs are only:

B2, Ba, B1 // If the object created in m1(x) is garbage collected before the System.out.println completes
, Ba, B1 // If the object created in m1(x) is not garbage collected

I think this output is also possible, but very unlikely:

, Ba, B1B2 // If the object created in m1(x) is garbage collected after System.out.println completes, before main returns
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic