• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Garbage Collector and Static Variables

 
Shivashankar Gurumurthy
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
I want to know answers for the following questions. Anybody please help me out in this regard.
1)How would garbage collection work on the static variables
2)Will the static variables be garbage collected at all?

Thanks
Shiva
 
Sanjeev Singh
Ranch Hand
Posts: 381
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Shiva,
Just now I was going through a SCJP forum and came through this thread.
Barry replied ..
When a class A is loaded an object is created representing the class. This object is an instance of the class Class. From this object you can obtain other objects representing the variables (both static fields and member fields) of the class A. All these objects are held in the heap. The only variables held on the stack are local variables of a method.

So now we should conclude that the static variables are GCed in the same way the instance variable is GCed.
The answer to the second part should be " every thing which resides on the heap are created and destroyed".
 
Anton Uwe
Ranch Hand
Posts: 122
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mhhh. I'm still considering what you mean with "static variables" and "garbage collected".

Let's take a look at this class:

As soon as someone uses Foo.str, the class loader of the JVM will load the Foo-class. A String-object will be created (on the heap!) and str will be set to refer to this String-object. str itself is on the heap,too, but in the object representing the FOO-class.
As soon as someone would execute i.e.

the old String object (the String-object with content "Hello World") is free for garbage collection.

The variable str will be existent as long as the class representation object will reside in the heap. It will "disappear" when the class Foo is unloaded (main thread and all user threads terminated/JVM shuts down).
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Variables aren't gc'ed at all. Only objects are gc'ed. A reference variable can *reference* an object, but it *is* not the object.
 
Vlado Zajac
Ranch Hand
Posts: 245
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Static variables are destroyed when the class is unloaded. This can occur when it's class loader is garbage collected.
 
Shivashankar Gurumurthy
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All
Thanks everyone for your prompt and patient replies
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic