group-icon
Java Developers
Group for Java developers and programmers. Ask questions and get answers related to Java programming
271 Members
Join this group to post and comment.
Archana Priyadarshini
Archana Priyadarshini
Computer Science
04 Feb 2019

Garbage collection in java

In Java, when an object is not referenced any more, garbage collection takes place and the object is destroyed automatically. For automatic garbage collection java calls either System.gc() method or Runtime.gc() method.

In Java, the programmers don’t need to take care of destroying the objects that are out of use. The Garbage Collector takes care of it.

Garbage Collector is a Daemon thread that keeps running in the background. Basically, it frees up the heap memory by destroying the unreachable objects.Unreachable objects are the ones that are no longer referenced by any part of the program.

We can choose the garbage collector for our java program through JVM options,

DHIRAJ LOTLIKAR
DHIRAJ LOTLIKAR
Information Technology
3mos ago

The main aim of Java garbage collector is to make memory efficient and easily useable for java application. It is done automatically in the backend, we don't have to do it manually. If there exist an unreferenced object then java garbage collector will reuse that memory automatically.

It  is the process of reclaiming the runtime unused memory automatically.

In java the unreferenced object can be in many way such as,

1) By nulling the reference: Suppose I created a object of class A and then I say a=null.

2) By assigning a reference to another: We create one more object of a which is b and a==b. Now the first object a is refered by b. So we have assigned the value of a to b. Then a is considered as garbage value.

3) By using anonymous object: If you are using anonymous object  like new A(); then it is assigned to java garbage collector.

There are two method in java garbage colletion 

1) finalize method(): Invoked each time before the object is garbage collected. Defined in object class.

2) gc() method: Invoke garbage collection. It is in system and runtime class.