Garbage Collector (GC) in Java: Heap Memory and Generations

👋 Hii Connections 📌𝗚𝗮𝗿𝗯𝗮𝗴𝗲 𝗖𝗼𝗹𝗹𝗲𝗰𝘁𝗼𝗿 (𝗚𝗖) 𝗶𝗻 𝗝𝗮𝘃𝗮 ❓ 𝗪𝗵𝗮𝘁 𝗶𝘀 𝗚𝗮𝗿𝗯𝗮𝗴𝗲 𝗖𝗼𝗹𝗹𝗲𝗰𝘁𝗼𝗿 (𝗚𝗖)? Garbage Collector (GC) is a part of JVM that automatically removes unused objects from Heap memory. ❓ 𝗪𝗵𝘆 𝗚𝗖 𝗶𝘀 𝗡𝗲𝗲𝗱𝗲𝗱? In C/C++ → Memory is manually freed using free() or delete() In Java → Memory allocation = new Memory deallocation = Automatic (by GC) Prevents: -> Memory leaks -> Dangling pointers -> Manual memory errors ❓ 𝗪𝗵𝗮𝘁 𝗶𝘀 𝗛𝗲𝗮𝗽 𝗔𝗿𝗲𝗮? Heap is the runtime memory where objects and instance variables are stored. Heap is divided into: 1️⃣ Young Generation 2️⃣ Old Generation ❓ 𝗪𝗵𝗮𝘁 𝗶𝘀 𝗬𝗼𝘂𝗻𝗴 𝗚𝗲𝗻𝗲𝗿𝗮𝘁𝗶𝗼𝗻? Young Generation is the part of the Heap memory where newly created objects are stored. -> Most objects are short-lived, so GC runs frequently here. -> Young Generation has: 1. Eden Space 2. Survivor S0 3. Survivor S1 ❓ 𝗪𝗵𝗮𝘁 𝗶𝘀 𝗘𝗱𝗲𝗻 𝗦𝗽𝗮𝗰𝗲? All new objects are created here. Example: Student s = new Student(); // Stored in Eden ❓ 𝗪𝗵𝗮𝘁 𝗶𝘀 𝗦𝘂𝗿𝘃𝗶𝘃𝗼𝗿 (𝗦𝟬 & 𝗦𝟭)? Stores objects that survive Minor GC One acts as 𝗙𝗿𝗼𝗺 𝗦𝗽𝗮𝗰𝗲, other as 𝗧𝗼 𝗦𝗽𝗮𝗰𝗲 After each Minor GC → they swap Object age increases If age reaches limit (~15) → moved to Old Generation ❓𝗪𝗵𝗮𝘁 𝗶𝘀 𝗢𝗹𝗱 𝗚𝗲𝗻𝗲𝗿𝗮𝘁𝗶𝗼𝗻? Old Generation is the part of the Heap memory where long-lived objects are stored. -> Cleaned by Major / Full GC. -> If memory not available → java.util.OutOfMemoryError 📌𝗚𝗖 𝗳𝗼𝗹𝗹𝗼𝘄𝘀 𝗠𝗦𝗖 𝗔𝗹𝗴𝗼𝗿𝗶𝘁𝗵𝗺! 1️⃣ Mark – Marks reachable objects 2️⃣ Sweep – Removes unreachable objects 3️⃣ Compact – Rearranges memory (removes gaps) Java learners 👉 Save it. Like it. Comment “JVM”. 🚀 🚀 Next post will be about Garbage Collection in Java - how JVM automatically manages memory! Follow and like to stay updated with the series 💙 #Java #GarbageCollection #100DaysOfCode

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories