What Is the Garbage Collector in Java

What is the garbage collector in Java?

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.

Understanding garbage collector in java

In the linked explanation the "sweep" step is actually not described.

Roughly speeking:

  1. mark: find the "root" object(s), and perform a traversal of the object graph, marking all objects, which are touched during the traversal.
  2. sweep: go through your heap from A to Z and delete all objects which aren't marked (sweep through your heap; or sweep the non-marked objects from your heap).

If you don't do sweep the memory is not freed, just marked as free (think of the "Trash bin" in your OS -> mark = put into trash bin; sweep = delete from trash bin).

Java:confused about CMS garbage collector

The garbage collector's task is to find objects that your program can no longer reach by following whatever chain of accessor steps, and to reclaim the memory occupied by them.

The Mark-Sweep GC does that the other way round: it first finds all objects that can still be reached, and then reclaim the memory of all the other objects.

Simplified Mark-Sweep algorithm (of course the real one is far more complex):

  • Start with all directly-reachable references, e.g. local variables on the stack (arguments and locals from all not-yet-finished method calls), static fields etc.
  • Mark the objects they point to.
  • Recursively inspect the newly-marked objects. Mark the objects referenced by their fields.
  • Repeat until you get no more new marks.
  • Loop over your memory object-by-object and reclaim the memory of every object without a mark.
  • Finally remove all marks.

Will stream classes or connections considered as a resource leak in Java

Yes you are right.

Garbage collection frees Java heap (memory) but close() frees OS resources used for open file (number of open files is limited on most system) and assures that the data is really written.

But many classes such as FileInputStream and RandomAccessFile are written with a finalize() method which ensures that IF an instance in garbage collected, close() will be called first. So in many cases, garbage collection does indirectly free up files, and it is often possible for programmers to be lazy about closing resources, because garbage collection usually cleans them up for you. Unfortunately.

The problem is that you can't control when this happens, and it may not happen at all. So if you have too many files open, the operating system may give you an error about that before the garbage collector gets around to closing them. Or if you want to move a file or delete it, immediately after reading it - the move or delete may fail, because at that moment you've still got the file open for reading.

Errors like this are often hard to reproduce reliably, because they depend on the timing of the garbage collector. So you get things which usually work fine, but sometimes fail mysteriously. Very annoying to debug. For this reason, it is stronly recommended to be sure to close() any stream/reader/connection or other closable resource you may be using, as soon as you are done with it. Preferably in a finally block, to ensure it happens even if some other error occurs in processing.

And with Java 7, there is an addition of AutoClosable interface, read more about it here.

Ref: http://www.coderanch.com/t/278165//java/InputStream-close-garbage-collection

Are Java Garbage Collectors specific to Major GC?

Collectors are implementation details of JVMs, the following only covers Oracle/OpenJDK Hotspot:

Recent collectors such as G1, ZGC, Shenandoah are highly integrated where all GC cycles (major/minor would be oversimplifying things here) are managed by code specific to that collector.

Some of the older collectors on the other hand are more modular and allow you to mix and match to some extent.
Jon Masamitsu's blog post Our Collectors gives an overview of pre-G1 collectors.
Note that some of those have been deprecated in jdk8 and removed in jdk9

How does Garbage Collection in Java work?

Should Object B and Object C now been
collected by the Garbage Collector?

Yes. Well, they are candidates for collection because there's no way to reach Object B and C through the root that is A.



Related Topics



Leave a reply



Submit