Mark-and-Sweep: Garbage Collection Algorithm

Last Updated : 10 May, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

There are many garbage collection algorithms that run in the background, of which one of them is mark and sweep.

All the objects which are created dynamically (using new in C++ and Java) are allocated memory in the heap. If we go on creating objects we might get Out Of Memory error since it is not possible to allocate heap memory to objects. So we need to clear heap memory by releasing memory for all those objects which are no longer referenced by the program (or the unreachable objects) so that the space is made available for subsequent new objects. This memory can be released by the programmer itself but it seems to be an overhead for the programmer, here garbage collection comes to our rescue, and it automatically releases the heap memory for all the unreferenced objects. 

Mark and Sweep Algorithm 

Any garbage collection algorithm must perform 2 basic operations. One, it should be able to detect all the unreachable objects and secondly, it must reclaim the heap space used by the garbage objects and make the space available again to the program. The above operations are performed by Mark and Sweep Algorithm in two phases as listed and described further as follows: 

  • Mark phase
  • Sweep phase

Phase 1: Mark Phase 

When an object is created, its mark bit is set to 0(false). In the Mark phase, we set the marked bit for all the reachable objects (or the objects which a user can refer to) to 1(true). Now to perform this operation we simply need to do a graph traversal, a depth-first search approach would work for us. Here we can consider every object as a node and then all the nodes (objects) that are reachable from this node (object) are visited and it goes on till we have visited all the reachable nodes.

  • The root is a variable that refers to an object and is directly accessible by a local variable. We will assume that we have one root only.
  • We can access the mark bit for an object by ‘markedBit(obj)’.

Algorithm: Mark phase 

Mark(root)
If markedBit(root) = false then
                     markedBit(root) = true
                                       For each v referenced by root
                                       Mark(v)

Note: If we have more than one root, then we simply have to call Mark() for all the root variables. 

Phase 2: Sweep Phase 

As the name suggests it “sweeps” the unreachable objects i.e. it clears the heap memory for all the unreachable objects. All those objects whose marked value is set to false are cleared from the heap memory, for all other objects (reachable objects) the marked bit is set to true. 
Now the mark value for all the reachable objects is set to false since we will run the algorithm (if required) and again we will go through the mark phase to mark all the reachable objects. 

Algorithm: Sweep Phase 

Sweep()
For each object p in heap
If markedBit(p) = true then
                  markedBit(p) = false
                                 else
                                     heap.release(p)

The mark-and-sweep algorithm is called a tracing garbage collector because it traces out the entire collection of objects that are directly or indirectly accessible by the program. 

Example: 

A. All the objects have their marked bits set to false. 
 

M&S_Fig1

B. Reachable objects are marked true

M&S_Fig2

C. Nonreachable objects are cleared from the heap. 

 

M&S_Fig3

Advantages of Mark and Sweep Algorithm are as follows: 

  • It handles the case with cyclic references, even in the case of a cycle, this algorithm never ends up in an infinite loop.
  • There are no additional overheads incurred during the execution of the algorithm.

Disadvantages of the Mark and Sweep Algorithm are as follows:

  • The main disadvantage of the mark-and-sweep approach is the fact that  normal program execution is suspended while the garbage collection algorithm runs.
  • Another disadvantage is that, after the Mark and Sweep Algorithm is run several times on a program, reachable objects end up being separated by many, small unused memory regions. Look at the below figure for a better understanding. 

HeapMemory

Here white blocks denote the free memory, while the grey blocks denote the memory taken by all the reachable objects. 

Now the free segments (which are denoted by white color) are of varying sizes let’s say the 5 free segments are of size 1, 1, 2, 3, 5 (size in units). 
Now we need to create an object which takes 10 units of memory, now assuming that memory can be allocated only in the contiguous form of blocks, the creation of an object is not possible although we have an available memory space of 12 units and it will cause OutOfMemory error

This problem is termed “Fragmentation”. We have memory available in “fragments” but we are unable to utilize that memory space. We can reduce the fragmentation by compaction; we shuffle the memory content to place all the free memory blocks together to form one large block. Now consider the above example, after compaction we have a contiguous block of free memory of size 12 units so now we can allocate memory to an object of size 10 units. 



Similar Reads

How to prevent objects of a class from Garbage Collection in Java
The garbage collector in Java is automatic, i.e the user doesn't have to manually free an occupied memory which was dynamically allocated. And how does a garbage collector decide which object is to be deleted? It's simple: the object which loses it's reference, is marked for deletion from the heap memory. For example, look at the following piece of
5 min read
Garbage Collection in Java
Garbage collection in Java is the process by which Java programs perform automatic memory management. Java programs compile to bytecode that can be run on a Java Virtual Machine, or JVM for short. When Java programs run on the JVM, objects are created on the heap, which is a portion of memory dedicated to the program. Eventually, some objects will
9 min read
Output of Java programs | Set 10 (Garbage Collection)
Prerequisite - Garbage Collection in Java Difficulty level : Intermediate In Java, object destruction is taken care by the Garbage Collector module and the objects which do not have any references to them are eligible for garbage collection. Below are some important output questions on Garbage collection. Predict the output of following Java Progra
4 min read
How to make object eligible for garbage collection in Java?
An object is eligible to be garbage collected if its reference variable is lost from the program during execution.Sometimes they are also called unreachable objects. What is reference of an object? The new operator dynamically allocates memory for an object and returns a reference to it. This reference is the address in memory of the object allocat
5 min read
Java Program to Get the Size of Collection and Verify that Collection is Empty
The size() and isEmpty() of java.util.Collection interface is used to check the size of collections and if the Collection is empty or not. isEmpty() method does not take any parameter and does not return any value. Example: Input:[99, 54, 112, 184, 2] Output:size = 5 and Collection is not empty Input:[] Output: size = 0 and Collection is emptysize(
2 min read
Difference Between Collection.stream().forEach() and Collection.forEach() in Java
Collection.forEach() and Collection.stream().forEach() are used for iterating over the collections, there is no such major difference between the two, as both of them give the same result, though there are some differences in their internal working. Collection.stream().forEach() is basically used for iteration in a group of objects by converting a
3 min read
Types of JVM Garbage Collectors in Java with implementation details
prerequisites: Garbage Collection, Mark and Sweep algorithm Garbage Collection: Garbage collection aka GC is one of the most important features of Java. Garbage collection is the mechanism used in Java to de-allocate unused memory, which is nothing but clear the space consumed by unused objects. To deallocate unused memory, Garbage collector track
5 min read
Z Garbage Collector in Java
Today, it's common for applications to respond to thousands or even millions of users concurrently. Such applications need immeasurable amounts of memory. However, managing all that memory may easily impact application performance. To overcome this issue java 11 includes a lot of improvements and changes in the GC(Garbage Collection) domain. Java 1
6 min read
Different Ways to Collect Garbage in Java HotSpot JVM
JDKs come with different JVM implementations (Oracle HotSpot, Eclipse OpenJ9, GraalVM, Jikes RVM, Codename One), and different garbage collector implementations with different tuning options (Serial, Parallel, CMS, G1, Z, Shenandoah). In this article, we will know more about the Garbage Collector, how it works, and the various types of GC available
7 min read
Reader mark(int) method in Java with Examples
The mark() method of Reader Class in Java is used to mark the stream as the checkpoint from where the stream read will start, once reset() is called. This method is not supported by all subclasses of Reader class. Syntax: public void mark(int readAheadLimit) Parameters: This method accepts a mandatory parameter readAheadLimit which is the limit on
3 min read
CharArrayReader mark(int) method in Java with Examples
The mark() method of CharArrayReader Class in Java is used to mark the stream as the checkpoint from where the stream read will start, once reset() is called. This method is not supported by all subclasses of CharArrayReader class. Syntax: public void mark(int readAheadLimit) Parameters: This method accepts a mandatory parameter readAheadLimit whic
3 min read
StringReader mark(int) method in Java with Examples
The mark() method of StringReader Class in Java is used to mark the stream as the checkpoint from where the stream read will start, once reset() is called. This method is not supported by all subclasses of StringReader class. Syntax: public void mark(int readAheadLimit) Parameters: This method accepts a mandatory parameter readAheadLimit which is t
3 min read
PushbackReader mark(int) method in Java with Examples
The mark() method of PushbackReader Class in Java is used to marks the current position of the PushbackReader. In the case of PushbackReader, this method always throws an exception as this method isn't supported by the PushbackReader. Syntax: public void mark(int readAheadLimit) Parameters: This method accepts a mandatory parameter readAheadLimit w
2 min read
ByteBuffer mark() methods in Java with Examples
The mark() method of java.nio.ByteBuffer Class is used to set this buffer's mark at its position. Syntax: public ByteBuffer mark() Return Value: This method returns this buffer. Below are the examples to illustrate the mark() method: Examples 1: // Java program to demonstrate // mark() method import java.nio.*; import java.util.*; public class GFG
2 min read
Buffer mark() methods in Java with Examples
The mark() method of java.nio.Buffer Class is used to set this buffer's mark at its position.Syntax: public Buffer mark() Return Value: This method returns this buffer.Below are the examples to illustrate the mark() method:Examples 1: Java Code // Java program to demonstrate // mark() method import java.nio.*; import java.util.*; public class GFG {
2 min read
CharBuffer mark() methods in Java with Examples
The mark() method of java.nio.CharBuffer Class is used to set this buffer's mark at its position. Syntax: public CharBuffer mark() Return Value: This method returns this buffer. Below are the examples to illustrate the mark() method: Examples 1: // Java program to demonstrate // mark() method import java.nio.*; import java.util.*; public class GFG
2 min read
DoubleBuffer mark() methods in Java with Examples
The mark() method of java.nio.DoubleBuffer Class is used to mark the current position of this DoubleBuffer as the mark of this buffer. Syntax: public DoubleBuffer mark() Return Value: This method returns this DoubleBuffer after setting the buffer's mark at the current position. Below are the examples to illustrate the mark() method: Examples 1: //
2 min read
FloatBuffer mark() methods in Java with Examples
The mark() method of java.nio.FloatBuffer Class is used to mark the current position of this FloatBuffer as the mark of this buffer. Syntax: public final FloatBuffer mark() Parameters: The method does not take any parameters. Return Value: This method returns this FloatBuffer after setting the buffer's mark at the current position. Below examples i
2 min read
IntBuffer mark() method in Java with Examples
The mark() method of java.nio.IntBuffer Class is used to mark the current position of this IntBuffer as the mark of this buffer. Syntax: public final IntBuffer mark() Parameter: The method do not take any parameter. Return Value: This method returns this IntBuffer after setting the buffer's mark at the current position. Below are the examples to il
2 min read
LongBuffer mark() method in Java with Examples
The mark() method of java.nio.LongBuffer Class is used to mark the current position of this LongBuffer as the mark of this buffer. Syntax: public LongBuffer mark() Parameter: This method do not accept any parameter. Return Value: This method returns this LongBuffer after setting the buffer's mark at the current position. Below are the examples to i
2 min read
ShortBuffer mark() method in Java with Examples
The mark() method of java.nio.ShortBuffer Class is used to mark the current position of this ShortBuffer as the mark of this buffer. Syntax: public ShortBuffer mark() Parameter: This method do not accept any parameter. Return Value: This method returns this ShortBuffer after setting the buffer's mark at the current position. Below are the examples
2 min read
BufferedInputStream mark() method in Java with Examples
The mark() method of BufferedInputStream class in Java is used to mark the current position in the input stream. Reset() method of the same class BufferedInputStream is called after the mark() method. Reset() fixes the position at the last marked position so that same byte can be read again. General Contract: The input stream somehow saves all the
3 min read
BufferedReader mark() method in Java with Examples
The mark() method of BufferedReader class in Java is used to mark the current position in the buffer reader stream. The reset() method of the same BufferedReader class is also called subsequently, after the mark() method is called. The reset() method fixes the position at the last marked position so that same byte can be read again. Syntax: public
3 min read
PushbackInputStream mark() method in Java with Examples
The mark() method of PushbackInputStream class in Java is used to mark the current position in the input stream. This method does nothing for PushbackInputStream. Syntax: public void mark(int readlimit) Overrides: This method overrides the mark() method of FilterInputStream class. Parameters: This method accepts single parameter readlimit that repr
2 min read
ByteArrayInputStream mark() method in Java with Examples
The mark() method in ByteArrayInputStream in Java is used to set a mark at the current position in the stream. This allows you to later reset the stream to this marked position using the reset() method. The mark() method is particularly useful when you need to read from a certain point and then return to that point later in the stream. Syntax: publ
3 min read
Finding minimum and maximum element of a Collection in Java
A Collection is a group of individual objects represented as a single unit. Java provides Collection Framework which defines several classes and interfaces to represent a group of objects as a single unit. These are: Finding minimum and maximum element of a Collection can be easily done using the Collections.min() and Collections.max() method. Thes
6 min read
Sorting collection of String and StringBuffer in Java
Sorting a collection of objects can be done in two ways: By implementing Comparable (Natural Order) e.g. Strings are sorted ASCIIbetically. meaning B comes before A and 10 is before 2.By implementing Comparator (Custom order) and it can be in any order.Using Collections.sort() method of Collections utility class. Read more about Comparable and Comp
2 min read
Iterator vs Collection in Java
Iterator and Collection, both has helped and comforted the programmers at many a times. But their usage and application has a very wide difference. 1. Iterator Declaration public interface Iterator Type Parameters: E - the type of elements returned by this iteratorIterators are used in Collection framework in Java to retrieve elements one by one. M
3 min read
Convert an Iterable to Collection in Java
Iterable and Collection have served to be of great use in Java. Iterators are used in Collection framework in Java to retrieve elements one by one and a Collection is a group of individual objects represented as a single unit. Java provides Collection Framework which defines several classes and interfaces to represent a group of objects as a single
4 min read
Non-generic Vs Generic Collection in Java
We will be discussing differences later prior let us understand what is generic Collection and non-generic Collection, and most importantly dealing with the implementation part as during implementation one can only really get the real understanding of the concept, henceforth the differences between them. Generics are basically the errors appearing
5 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg