Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question on Garbage Collection

 
George Koshy
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The below question has been taken from http://www.geocities.com/SiliconValley/Orchard/9362/java/q_a/index1.html
(Part of Barry Boone site) Question no. 60

1. public void method(String s){
2. String a,b;
3. a = new String("Hello");
4. b = new String("Goodbye");
5. System.out.println(a + b);
6. a = null;
7. a = b;
8. System.out.println(a + b);
9. }
Where is it possible that the garbage collector will run the first time?


A. Just before line 5
B. Just before line 6
C. Just before line 7
D. Just before line 8
E. Never in this method

The provided answer is c , i feel the answer is b , because a temporary string object has been created in the System.out.println (a + b )

Comments please ......
 
Fletcher Estes
Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're right - temporary objects are available for garbage collection immediately after they are used. You can confirm this by using the System.gc() and Runtime.getRuntime().freeMemory() methods. Check how much memory is available just after the temporary object is created, call the garbage collector, then check how much memory is available again - it should be more as the temporary object will probably be garbage collected.
 
Corey McGlone
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Fletcher Estes:
You can confirm this by using the System.gc() and Runtime.getRuntime().freeMemory() methods. Check how much memory is available just after the temporary object is created, call the garbage collector, then check how much memory is available again - it should be more as the temporary object will probably be garbage collected.


This is good advice, but you can't always rely on this. Invoking System.gc suggests that the garbage collection process should execute but doesn't require it to. You're never guaranteed that it will execute. So it's quite possible that before and after your call to System.gc that you'll have the same amount of memory available.

However, you are absolutely correct, the temporary String object is eligible for collection immediately prior to line 6.
 
Tybon Wu
Ranch Hand
Posts: 84
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I agree that the answer should be b too. The concatenation a + b creates a temporary StringBuffer object, which in turn creates a new String object representing the result, and both are eligible for garbage collection.
 
George Koshy
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thnx for your time Guys .....
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic