×

Advanced Coding & Software Engineering Program

Duration: 1 Year (12 Months)

Join our premium 1-year program to master cutting-edge technologies and become an industry-ready Software Engineer!

Course Coverage

  • Languages: C, C++, Java, JavaScript, Python
  • Web Technologies: HTML, CSS, Bootstrap 5, MERN Stack, Full Stack Development
  • Databases: MySQL, MongoDB
  • Data Science Libraries: Pandas, NumPy
  • Development Tools: Visual Studio Code, IntelliJ IDEA, PyCharm, Postman, Git, GitHub
  • Cloud Platforms: Vercel, MongoDB Atlas

Program Highlights

  • Live Classes: Interactive sessions with real-time doubt resolution
  • Hands-On Sessions: Practical coding exercises to build real-world skills
  • Industry Experts: Learn from professionals with years of experience
  • Live Project: Work on real-world projects to apply your skills
  • Get Certificate: Earn a professional certificate upon program completion

Course Fee: Only ₹1020 / month
Limited Period Offer!

Basics of Java Memory Management and Garbage Collection



Last Updated on: 27th Nov 2025 14:19:25 PM

Every Java program requires memory to store data, variables, objects, classes, and the instructions needed for execution. When an application becomes large, managing memory efficiently becomes crucial for performance and stability.

 

Java takes care of memory automatically using:

✔ Automatic Memory Allocation

✔ Automatic Memory Deallocation (Garbage Collection)

Well-structured Memory Model (Heap, Stack, Method Area, MetaSpace)

 

This reduces developer effort and prevents common errors like:

  • Memory leaks

  • Dangling pointers

  • Manual deallocation mistakes (as in C/C++)

 

Java’s Memory Management + Garbage Collector (GC) ensures:

  • Efficient memory usage

  • No need for manual free()

  • Faster development

  • Stable long-running applications like servers, games, Android apps, banking systems

Java is heavily used in enterprise systems because its memory management is fast, reliable, and automatic.

 

Why Memory Management Is Important?

In real-life applications like:

  • Amazon, Flipkart

  • Banking servers

  • Android apps

  • Social media platforms

Thousands of objects are created every second—user sessions, requests, cart items, API responses, etc.

 

Java's memory management ensures:

  • No System Crash 

  • Faster Response

  • Efficient resource usage

  • Automatically removes unused objects

 

Java Memory Structure (JVM Memory Model)

Java divides memory into logical areas:

 

+--------------------------------+
|      Method Area / MetaSpace   |
+--------------------------------+
|            Heap                 |
+--------------------------------+
|          Java Stack             |
+--------------------------------+
|      PC Register (per thread)  |
+--------------------------------+
|     Native Method Stack        |
+--------------------------------+

 

1. Method Area (MetaSpace)

Contains:

  • Class bytecode

  • Method definitions

  • Static variables

  • Constant pool

  • Code of constructors

Since Java 8, it's stored in native memory → called MetaSpace.

✔ Stores class-level information
✔ Not garbage collected frequently

 

2. Heap Memory (Objects Live Here)

This is where Java stores all objects.

 

Heap is divided into:

 

a) Young Generation

Where new objects are created.

  • Eden Space

  • Survivor Space S0

  • Survivor Space S1

Minor GC (fast) cleans unreferenced objects from Young Gen.

 

b) Old Generation (Tenured Space)

Objects that survive many Minor GCs move here.

Major GC (slower) cleans Old Gen.

 

c) Permanent Generation (Java 7 and older)

Class metadata, removed in Java 8 and replaced by MetaSpace.

 

3. Stack Memory

Each thread gets its own stack.

 

Stores:

  • Local variables

  • Method calls

  • Reference variables

Stack = Fast, last-in-first-out (LIFO).

 

4. PC Register

Stores address of current executing instruction for each thread.

 

5. Native Method Stack

Used by JNI (Java Native Interface) when calling C/C++ code.

 

Memory Management Example

class Student {
    String name;
}

public class Main {
    public static void main(String[] args) {
        Student s1 = new Student();  // Stored in Heap
        int x = 10;  // Stored in Stack
    }
}

 

  • Object s1 → Heap

  • Reference s1 + x → Stack

When main() ends, x and s1 reference is removed from stack.
Object is eligible for Garbage Collection.

 

Garbage Collection (GC) in Java

Garbage Collection removes objects that are no longer reachable.

✔ Automatically clears unused objects

✔ Prevents memory leaks

✔ Frees heap space

✔ Managed by JVM, not developer

GC runs in the background as a low-priority daemon thread.

 

 

How JVM Decides Which Objects to Delete?

JVM uses Reachability Analysis:

Object is deleted if:

  • No reference variable points to it

  • No active thread can access it

  • Object is not in use anymore

Example:

Student s1 = new Student();
s1 = null;   // Eligible for GC

 

How to Make Object Eligible for GC?

1. Nullifying Reference

Employee e = new Employee();
e = null;

 

2.Reassigning Reference

Employee e1 = new Employee();
Employee e2 = new Employee();
e1 = e2;  // first object eligible for GC

 

3. Leaving Scope

void show() {
    Person p = new Person();
} // p destroyed after method ends → GC eligible

 

Types of Garbage Collectors in Java

Modern JVM provides multiple GCs:

 

1. Serial GC

Single-threaded
Used in small applications.

 

2. Parallel GC

Multi-threaded
Faster than Serial GC.

 

3. CMS (Concurrent Mark Sweep)

Old, deprecated.
Used for low-latency applications.

 

4. G1 GC (Garbage First)

Default for modern JVM.
Fast + Parallel + Low pause times.
Used in enterprise applications.

 

5. ZGC (Z Garbage Collector)

Near-zero pause time.
Great for large memory systems (e.g., >100GB RAM).

 

6. Shenandoah GC

Red Hat’s low-pause collector.

 

GC Process (How Garbage Collector Works)

Garbage Collection happens in 3 steps:

1. Mark → Find reachable objects  
2. Sweep → Remove unreferenced objects  
3. Compact → Rearrange memory to avoid fragmentation

 

Calling Garbage Collector Manually

You can request GC, but it’s not guaranteed:

System.gc();

JVM decides whether to run GC or ignore request.

 

Real-Life Example of Garbage Collection

Online Shopping Cart (Amazon/Flipkart)

  • User adds items → Objects created

  • User removes items → Objects become unused

  • Session ends → Unused objects are cleaned

GC removes:

  • Old cart objects

  • Previous user session objects

  • Temporary API response objects

This keeps the system fast even with millions of users.

 

Android Apps

When you minimize or close an app:

  • Unreferenced Activities

  • Destroyed Fragments

  • Old bitmaps

All become garbage → GC clears automatically.

 

Bank Server

Every ATM request creates:

  • Request object

  • Customer object

  • Transaction object

After completion:

✔ Old objects cleared
✔ Memory recovered
✔ Server remains fast even with 10,000+ requests/min

 

Difference Between Stack & Heap

Feature Stack Heap
Stores Local variables, references Objects, instance variables
Access Speed Very fast Slower
Managed By JVM Garbage Collector
Memory Size Small Large
Thread Safety Yes (each thread has own stack) No
Lifetime End of method execution Until object becomes unreachable

 

Common Memory Problems (Even in Java)

 

❗ 1. Memory Leak

Occurs when objects are not cleared because references still exist.

Example:
Large ArrayList that keeps growing but never cleared.

 

❗ 2. OutOfMemoryError

Occurs when JVM cannot allocate new objects in heap.

Example:
Huge image files
Infinite loops creating objects
Heavy caching

 

❗ 3. StackOverflowError

Occurs when:

  • Too deep recursion

  • Infinite method calls

 

Best Practices to Avoid Memory Issues

✔ Avoid unnecessary object creation
✔ Use StringBuilder instead of String concatenation
✔ Close streams, connections, sessions
✔ Use weak references in caching
✔ Release large resources after use
✔ Use thread pools

 

Conclusion

Java Memory Management and Garbage Collection simplify the work for developers and ensure stable performance for real-world applications.
By understanding:

  • JVM Memory Model

  • Heap & Stack

  • GC types

  • Memory leaks

  • Best practices

You can build efficient, scalable, and high-performance Java applications.

 

Keep practicing — you're doing amazing!

Happy Coding!    yes


Online - Chat Now
Let’s Connect

Inquiry Sent!

Your message has been successfully sent. We'll get back to you soon!

iKeySkills Logo