Garbage Collection in Java (Mark and Sweep Algorithm)

Sharing is Caring

Garbage, in case of Computer Science, refers to data, object or any other part of memory that will not be used in any further program. Garbage Collection in Java is performed automatically.
Normally memory has much space according to programmer’s requirement but sometimes when there is a lot of unused in the memory area, it results in slow processing.

Garbage Collection-

Garbage Collection is a form of Memory Management, that is the job of the system.
That’s why it is called Automated Memory Management.
Garbage Collector tries to free memory space occupied by programs and data object that are no longer accessed by any Program or by system communication.

Garbage Collection in Java-

Garbage Collection In Java
In Java, Garbage collector runs automatically in the lifetime of a java program, It frees the allocated memory that is not used by running process.
In C language and other old languages, it is the responsibility of coder(Programmer) to free memory time to time using free(); function.
You can manually run garbage collector in java, there is a method in System class named void gc();
It suggests JVM(java virtual machine) collect currently unused memory.
System.gc(); is logically equal to Runtime.getRuntime.gc();

Mark and Sweep-

There are two algorithms for garbage collection- Mark and Sweep also known as Marking and Collection phase of the garbage collector.
When all available memory has been exhausted and execution of the program is suspended for a while then mark-and-sweep algorithm marks and collects all the garbage values and memory space.
Once all garbage is marked then it is collected and the process resumes.
This is the process of Garbage Collection in Java and same for many other Object Oriented languages.

Related Posts

0 thoughts on “Garbage Collection in Java (Mark and Sweep Algorithm)”

Leave a Reply

Your email address will not be published. Required fields are marked *