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.
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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 andFiles, but after a certain time, those objects are not used anymore. For example, take a look at the following code:In the above code, the
String sis being created on each iteration of theforloop. This means that in every iteration, a little bit of memory is being allocated to make aStringobject.Going back to the code, we can see that once a single iteration is executed, in the next iteration, the
Stringobject 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
mallocandfree. 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.