Welcome back to Java Code OnlineJava Code Online. The garbage collector is one of the best things in Java. In Java every Object lives on a heap. Heap is the play area of Objects. Whenever we create Objects, some area on the heap is allocated to this new Object. But what will happen, when this Object is of no use.
I mean to say that, when the Object refers nothing, then it consumes unnecessary space on the heap, which must be freed. This space could be used by other Objects, and also helps the JVM in speeding up the operations of processing.
This is where the garbage collector comes into picture. The Garbage collector in Java, checks at regular intervals about the Objects that are no more referenced by any variable. These Objects are eligible for Garbage collection. Garbage Collector checks for the Objects that are unreachable for the program, and so are consuming unnecessary space, so Garbage Collector considers these Objects as Garbage, and so it collects them. Thereby freeing space on the heap.
For example, if I say that:-
Object a = new Object();
This line of code allots space on the heap for the new Object. But suppose that later in the code, we say that:-
a = null;
This statement will cause the reference of this Object to refer null, and so the Object is lost in the heap and is now unreachable. This Object is now eligible for Garbage collection, so that space could be freed on the heap. This space helps the JVM in performing better and faster.
I hope that this article was helpful in explaining you the role of Garbage Collector in Java. If you liked this article, then do leave a comment. For more information on Java, keep buzzing Java Code Online.
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.