views:

192

answers:

8

I am new to Java and confused about the garbage collector in Java. What does it actually do and when does it comes into action. Please describe some of the properties of the garbage collector in Java.

+8  A: 

It frees memory allocated to objects that are not being used by the program any more - hence the name "garbage". For example:

public static Object otherMethod(Object obj) {
    return new Object();
}

public static void main(String[] args) {
    Object myObj = new Object();
    myObj = otherMethod(myObj);
    // ... more code ...  
}

I know this is extremely contrived, but here after you call otherMethod() the original Object created is made unreachable - and that's "garbage" that gets garbage collected.

In Java the GC runs automatically, but you can also call it explicitly with System.gc() and try to force a major garbage collection. As Pascal Thivent points out, you really shouldn't have to do this and it might do more harm than good (see this question).

For more, see the wikipedia entry on Garbage collection and Tuning Garbage Collection (from Oracle)

NullUserException
AFAIK `System.gc()` does not force GC to run.
Itay
+1 for the good code example. Note that it's perfectly valid for the GC to destroy `myObj` before the call to `otherMethod` takes place, because `myObj` is no longer accessible at that point.
Billy ONeal
@Italy I believe that's implementation specific.
NullUserException
I believe one should not call `System.gc()`, the whole point of having a GC is to not have to do that.
Pascal Thivent
@Pascal Good point; I incorporated it into the answer.
NullUserException
+3  A: 

garbage collector implies that objects that are no longer needed by the program are "garbage" and can be thrown away.

Yogesh
+3  A: 

Garbage Collector is part of JRE that makes sure that object that are not referenced will be freed from memory.
It usually runs when you app runs out of memory. AFAIK it holds a graph that represents the links between the objects and isolated objects can be freed.
To save performance the current objects grouped into generations, each time GC scans an object and finds that it is still referenced its generation count incremented by 1 (to some max maximum value, 3 or 4 i think) , and the new generation are scanned first (the shortest the object in memory the more probably it is no longer needed) so not all objects being scanned every time GC run.
read this for more information.

Itay
@quantumSoup are you possitive on this? I believe some kind of garbage collection (a more expensive one) only happens when the heap fills.
Pablo Fernandez
@quantumSoup - that depends on the JRE's GC implementation. In many cases, the GC *does not* run constantly. Instead, it runs when your app is unable to allocate an object because the heap is full. Recent HotSpot JVMs do include a parallel GC, but it is not enabled by default.
Stephen C
This answer concentrates too much on the mechanism. The question was "What is the garbage collector", not "How does the garbage collector operate"
Billy ONeal
@quantum: neutralised your -1,because: Learning, that is, what this page is for, right? To learn you need to make mistakes. Punishing mistakes makes people not learn. Hope, you can agree in that point. And maybe you did a mistake here.
erikb
@erikb: By that logic there would never be any downvotes. And downvotes are necessary to weed out relatively poor answers. The OP is obviously a beginner, and the specific inner workings of the GC simply aren't important to the question asked. Since this answer doesn't answer the question asked (it answers a different one), downvotes are perfectly justified.
Billy ONeal
@Billy: I agree on using downvotes to weed out poor answers. I just don't think that a mistake nessesarily and always makes a poor answer. Here, in this case are obvious reasons for a GC to not run all the time, while a situation dependend execution itself probably also has disadvantages. It is valuable to discuss that point, especially since yosanu wanted to know more about GC's attributes. This is one. Also, Itay does not seem to be the 12 year old "My guess is better then your knowledge" type. I did not actually value his unedited post an upvote, but also thought it far above a downvote.
erikb
A: 

Useful explanation can be found here http://www.roseindia.net/java/example/java/io/code-for-garbage-collection.shtml

wmitchell
+1  A: 

The garbage collector allows your computer to simulate a computer with infinite memory. The rest is just mechanism.

It does this by detecting when chunks of memory are no longer accessible from your code, and returning those chunks to the free store.

EDIT: Yes, the link is for C#, but C# and Java are identical in this regard.

Billy ONeal
There's actually a question on SO about the difference between java and C#'s GC: http://stackoverflow.com/questions/492703/c-vs-java-garbage-collector
NullUserException
@NullUserException: The link is more about GC in general, rather than C#'s GC specifically, though there are a few C# specific things there. The point though, is that you're simulating a computer with unlimited memory.
Billy ONeal
A: 

Garbage Collection in Java (and other languages/platforms as well) is a way for the java run-time environment (JRE) to reuse memory from java objects that are no longer needed. Simplistically, when the JRE initially starts up it asks the Operating System (O/S) for a certain amount of memory. As the JRE runs your application(s) it uses that memory. When your application is done using that memory, the JRE's "Garbage Collector" comes along and reclaims that memory for use by different parts of your existing application(s). The JRE's "Garbage Collector" is a background task that is always running and tries to pick times when the system is idle to go on its garbage runs.

A real world analogy would be the garbage men that come to your house and pick up your recyclable garbage... eventually, its reused in other ways by yourself and/or other people.

Al Dass
+2  A: 

The garbage collector is a program which runs on the Java Virtual Machine which gets rid of objects which are not being used by a Java application anymore. It is a form of automatic memory management.

When a typical Java application is running, it is creating new objects, such as Strings and Files, but after a certain time, those objects are not used anymore. For example, take a look at the following code:

for (File f : files) {
    String s = f.getName();
}

In the above code, the String s is being created on each iteration of the for loop. This means that in every iteration, a little bit of memory is being allocated to make a String object.

Going back to the code, we can see that once a single iteration is executed, in the next iteration, the String object that was created in the previous iteration is not being used anymore -- that object is now considered "garbage".

Eventually, we'll start getting a lot of garbage, and memory will be used for objects which aren't being used anymore. If this keeps going on, eventually the Java Virtual Machine will run out of space to make new objects.

That's where the garbage collector steps in.

The garbage collector will look for objects which aren't being used anymore, and gets rid of them, freeing up the memory so other new objects can use that piece of memory.

In Java, memory management is taken care of by the garbage collector, but in other languages such as C, one needs to perform memory management on their own using functions such as malloc and free. Memory management is one of those things which are easy to make mistakes, which can lead to what are called memory leaks -- places where memory is not reclaimed when they are not in use anymore.

Automatic memory management schemes like garbage collection makes it so the programmer does not have to worry so much about memory management issues, so he or she can focus more on developing the applications they need to develop.

coobird
A: 
bala sreekanth
Reference counting is one lousy way to implement GC. I don't think any major JVM implementation uses this.
NullUserException