what is garbage collector in java and how can we use it [duplicate]
Possible Duplicate:
What is the garbage collector in Java?
what is garbage collector in java and how can we use it
The garbage collector manages memory for you. It runs on a background thread while your code is running. You don't usually interact with it directly. You "use" it simply by running in the JVM.
This whitepaper has all the information you need about Garbage Collection in the Java HotSpot VM. If you come across any concept that's unfamiliar just search for it in Wikipedia or continue this thread.
You can't "use" garbage collection. It's a fundamental part of the language and its object model.
To clarify this, let us only consider class types (like String
and Integer
), and ignore fundamental types (like int
and char
). (Array types are also considered class types.) Suppose T
is such a class type.
In Java, unlike in other languages, you can never have a variable of class type. Whenever you declare a variable T x;
, x
is in fact a sort of "tracked reference". That reference can be null
, or it can refer to an existing object of type T
. But the object itself must always be explicitly, dynamically created:
T x = new T();
That object, the one to which x
refers, lives in some magic, managed part of your computer that you cannot manipulate directly. You can create further references, though:
T y = x; // another reference to the same object
Now a natural question arises: What happens to the object when there are no more references? The answer is garbage collection: When there are no further references to an object, it becomes eligible to be cleared up at a later, non-deterministic point in time. And that is the only way in which the resources associated with an object can ever be recovered.
Without garbage collection, you could basically not have any objects at all in Java in any well-defined, robust way.
精彩评论