• 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
  • Ron McLeod
  • Paul Clapham
  • Jeanne Boyarsky
  • Liutauras Vilda
Sheriffs:
  • Rob Spoor
  • Bear Bibeault
  • Tim Cooke
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:
  • Frits Walraven
  • Himai Minh

garbage collection?

 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I am wondering what I shall do if I want to collect garbage on time so that the application won't run out of memory. I think it's very important for a software product to sustain stress test.
In the methods, do I need to set variables to null before leaving? or those variables are automatically discarded and the corresponding referenced objects will be garbage collected(later)? Is there any other thing I shall do for this?
Thanks!
 
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Garbage collection of an object is only possible when an object no longer has a reference to it. Variables lose their reference by a couple of means. They can be dereferenced by losing scope, such as when you leave any block of code in which the variable was declared such as a method, try or catch block, if or else blocks, etc. They can be dereferenced because of reassignment of the reference to another object. Or, they can be manually deferenced by setting the reference to null. In most situations, this will not be necessary, although in certain rare situations, assisting the garbage collector by dereferencing an object can become necessary.
By the way, you can not force a garbage collection. You can ask for one to occur, but you have no guarantees. Of course, a GC is supposed to occur before things get bad...
 
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I tend to agree with you regarding variable scope and garbage collection. However, in the "Java 2 Exam Cram" book, page 163 (chapter 8 question 7) It states that, in a code block in a method, "...even though [a] variable [can go] out of scope... [it] still has a reference to the [object]."
I think this question's answer is wrong, but here goes...
For those who don't have this book, the method is as follows, and the variable in question is "tmp":
public void countDown()
{
for (int i=10 ; i>=0 ; i--)
{
String tmp = Integer.toString(i);
System.out.println(tmp);
}
System.out.println("BOOM!");
}
The question is, at the "BOOM!" line, how many String objects created in the "tmp = " line are eligible for GC?
The answer suggested is 10, but I think 11 is correct. Any comments?
 
"The Hood"
Posts: 8521
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Wes,
11 loops are executed in this case, but the LAST loop created a string that is still referenced in the tmp variable so is not available for the gc().
Rich,
The garbage collector's job is to clean up the heap where objects are created. When the reference to the object is no longer held in some variable then it is available to be collected. You set a variable to null to make the object available for collecting, not the variable.
Variables are created on the stack. They do not get cleaned up by the garbage collector at all. It is valid for a variable to have a null value, you can't have it disappear just because of that. They have to go out of scope to be cleaned up, and then the whole stack for the scope is zapped. It would be very inefficient for the garbage collector to do this.
Alex,


In the methods, do I need to set variables to null before leaving? or those variables are automatically discarded and the corresponding referenced objects will be garbage collected?


Setting the variable to null is a good idea for variables that will stay in scope for a long time, but when the stack is zapped the object is not referenced by it anymore. So objects only referenced by variables in methods will get cleaned up after the method goes out of scope, with no interference from you. Objects referenced by variables outside of methods may live MUCH longer, these you might want to worry about.
 
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Cindy ia correct, I just want add a note into it.
You should assign null to objects that are no longer in use. Otherwise if you allow live, accessable reference to un-needed objects, this will not allow garbage collector to collect those references. Therefore it is always a good idea to explicity assign null to those references. This avoids memory leaks.
 
Ranch Hand
Posts: 154
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
just being picky here Rich, but setting a variable to null isn't dereferencing it. Dereferencing is getting the object reffered to by a reference, like 's.toString()' would be dereferencing the variable s.
(only spotted this coz we had a discussion about it a couple of weeks ago: http://www.javaranch.com/ubb/Forum1/HTML/000902.html)
 
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
What I think is that b4 reaching line Boom the variable tmp goes out of scope and the object to which it points is also availible for GC, it makes 11.
AM I RIGHT?
 
author
Posts: 3252
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Yasir Qureshi:
What I think is that b4 reaching line Boom the variable tmp goes out of scope and the object to which it points is also availible for GC, it makes 11.
AM I RIGHT?


No you are not.
The implicit assumption you're making is that local variables, such as "tmp", are allocated on the stack as they come in scope, and deallocated as they go out of scope. If that were the case, then at the "BOOM!" line, "tmp" would no longer exist.
This is in fact not true. As I understand it, the JVM will allocate stack space for all local variables the moment you start executing countDown(). They are only deallocated when you leave the method. So the lifetime (as opposed to the scope) of the "tmp" variable is the entirety of the countDown() method.
(Note that in her explanation, Cindy says "scope" a couple of times where I would say "lifetime". I might very well be the one mixing my terminology up, in which case I apologise.)
Of course, you and I both know that at the "BOOM!" line, "tmp" is no longer visible and the String it refers to could safely be garbage collected. In the interest of efficiency, however, the gc doesn't analyse things to this detail. As far as it is concerned the 11th String is referenced by a local variable on the stack and not eligible for garbage collection.
- Peter
 
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In a nutshell there are 3 things you can do to facilitate garbage collection:
1. When you�re done with a reference to an object, set it to null. This way that object is marked for garbage collection.
2. Implement the finalize method for your complex objects. Here you could set all object references that this object used to null. The finalizer is the last thing that is called before the garbage collector reclaims the memory for the object. By the way, when one implements a finalize method, one is overriding the finalize method from the superclass Object.

3. You can suggest that the gc be ran with: System.gc() or Runtime.getRuntime.gc(). Java does not guarantee which object's finalizer will execute first. Garbage collection can be CPU intensive.
Hope this helps. Let me know if you have more questions.

Additional information:

Garbage collector is a low priority daemon thread (one that runs for the benefit of other threads.) The java language specification strangely, doesn't lay down the law on how garbage is to be collected. This way every implementer of a JVM is allowed to pursue the optimal method of gc.
Hope this helps.

Originally posted by Alex Guo:
I am wondering what I shall do if I want to collect garbage on time so that the application won't run out of memory. I think it's very important for a software product to sustain stress test.
In the methods, do I need to set variables to null before leaving? or those variables are automatically discarded and the corresponding referenced objects will be garbage collected(later)? Is there any other thing I shall do for this?
Thanks!


 
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Poor Bill Brogden wrote this question back in the dawn of time (well, 1997 really) and has been plagued with these discussions ever since. Please read the commentary he has posted about this question here. In a nutshell - it depends on the JDK. Some systems can collect all 11 objects, and others collect only 10. I (and many others) would argue that certainly all 11 are eligible for collection; whether they actually are collected basically depends on how good the GC is.
 
Cindy Glass
"The Hood"
Posts: 8521
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Peter,
You used the word "lifetime" (good word) so I looked up the correct term - I believe it is the "Frame" of the variable. The "lifetime" (not the scope) of a variable is determined by the frame that it is created in per method.
From the JVM Spec 3.6


A new frame is created each time a Java method is invoked. A frame is destroyed when its method completes, whether that completion is normal or abnormal (by throwing an exception). Frames are allocated from the Java stack (�3.5.2) of the thread creating the frame. Each frame has its own set of local variables (�3.6.1) and its own operand stack (�3.6.2).


Just to make sure, I went through the whole JVM Spec looking for references to blocks of code and stacks and frames, and there is nothing that indicates that a block of code would get it's own stack (that would be the only way that the variable WOULD be deallocated when the block completes). The closest that it comes is when it says:


The local variable effectively ceases to exist when the execution of the block or for statement is complete.


Which just describes that it goes out of scope.
http://java.sun.com/docs/books/vmspec/html/Overview.doc.html#17257
 
Peter den Haan
author
Posts: 3252
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Cindy, Jim, thank you dragging up those resources and xrefs. I think it's clear now (some would probably use the words "beaten to death")... very instructive. Thanks again.
- Peter
 
You showed up just in time for the waffles! And this tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic