0% found this document useful (0 votes)
2 views25 pages

MemoryManagement Java

Uploaded by

Rakesh kumar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views25 pages

MemoryManagement Java

Uploaded by

Rakesh kumar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

☕ Java Programming — Study Notes

Java Memory Management


& Object Life Cycle
Heap • Stack • Method Area • Garbage Collection • GC Tuning • Memory Leaks
Java Memory management:
-----
Object
Variable
class related(static)

Memory Management is one of the most important Java concepts. Every Java developer should understand where
objects are stored, how memory is allocated, how objects are destroyed, and how Java automatically
manages memory. It is a common interview topic because it affects application performance and stability.

What is Memory Management?

1. Memory Management is the process of allocating, using, and releasing memory while a Java program is
running.
2. Java automatically manages memory, so programmers do not need to manually allocate or free memory
like in C or C++.
3. The Java Virtual Machine (JVM) is responsible for managing memory.
4. Whenever a program creates an object using the new keyword, JVM allocates memory for that object.
5. Variables, objects, methods, and classes are stored in different memory areas inside the JVM.
6. Memory is divided into several parts such as Method Area, Heap Memory, Stack Memory, Program
Counter (PC) Register, and Native Method Stack.
7. Every time a method is called, a new stack frame is created in Stack Memory.
8. Objects created using the new keyword are stored in Heap Memory.
9. Local variables and method parameters are stored in Stack Memory.
10. Class information, static variables, and constant pool are stored in the Method Area.
11. Java automatically removes unused objects using the Garbage Collector (GC).
12. Proper memory management prevents memory leaks and improves application performance.
13. Java developers should avoid creating unnecessary objects to reduce memory usage.
14. Understanding memory management helps in debugging OutOfMemoryError and StackOverflowError.
15. Efficient memory management makes Java applications faster, more scalable, and easier to maintain.

JVM Memory Structure


1. Heap Memory

1. Heap Memory is the largest memory area in the JVM.


2. All objects and arrays created using the new keyword are stored in the Heap.
3. Every object occupies some space depending on its fields.
4. Heap Memory is shared among all threads.
5. Objects remain in the Heap until they are no longer reachable.
6. The Garbage Collector removes unused objects from the Heap.
7. Heap Memory is created when the JVM starts.
8. Heap Memory is destroyed when the JVM terminates.
9. Creating too many objects can increase memory usage.
10. If Heap Memory becomes full, Java throws OutOfMemoryError.
11. Developers should reuse objects when appropriate instead of creating unnecessary ones.
12. Heap Memory is the primary area managed by the Garbage Collector.

Heap Example
class Student {

String name;

Student(String name) {
[Link] = name;
}
}

public class HeapExample {

public static void main(String[] args) {

Student s1 = new Student("Rakesh");


Student s2 = new Student("Aman");

[Link]([Link]);
[Link]([Link]);
}
}
Memory Representation
Stack Memory Heap Memory

s1 -----------------------> Student("Rakesh")

s2 -----------------------> Student("Aman")

The variables s1 and s2 are stored in the Stack, while the actual Student objects are stored in the Heap.

2. Stack Memory

1. Stack Memory stores method execution information.


2. Every method call creates a new stack frame.
3. Local variables and method parameters are stored inside the stack frame.
4. Each thread has its own separate Stack Memory.
5. Stack Memory follows the Last In, First Out (LIFO) principle.
6. When a method finishes, its stack frame is automatically removed.
7. Stack allocation is very fast.
8. Stack Memory stores references to objects, not the objects themselves.
9. Recursive methods can create many stack frames.
10. Too many recursive calls can cause StackOverflowError.
11. Stack Memory is automatically managed by the JVM.
12. Developers cannot manually delete stack frames.
Stack Example
public class StackExample {

static void display() {


int x = 10;
[Link](x);
}

public static void main(String[] args) {

display();
}
}
Memory Representation
Stack

main()

display()

x = 10

Method Ends

Stack Frame Removed

3. Method Area

1. The Method Area stores class-level information.


2. It contains class metadata.
3. Static variables are stored here.
4. Method bytecode is stored here.
5. Runtime Constant Pool is part of the Method Area.
6. Only one Method Area exists per JVM.
7. It is shared among all threads.
8. The JVM creates it when the application starts.
9. Class information remains until the class is unloaded.
10. Developers indirectly use it through classes and static members.
Example
class Employee {

static String company = "Google";

int id;
}

Method Area

Employee Class

company = "Google"

Heap

Employee Object

4. Program Counter (PC) Register

 Each thread has its own PC Register.


 It stores the address of the current JVM instruction being executed.
 It helps the JVM know which instruction to execute next.
 During method execution, the PC Register updates continuously.
 It is essential for multithreading because each thread executes independently.

5. Native Method Stack

 Stores information for native methods.


 Native methods are written in languages like C or C++.
 Used when Java interacts with operating system libraries.
 Separate from the normal Java Stack.
 Managed by the JVM for native code execution.

Garbage Collection (GC)

1. Garbage Collection is the process of automatically removing unused objects from Heap Memory.
2. It prevents memory leaks caused by forgotten object deallocation.
3. Java programmers do not manually free memory.
4. The Garbage Collector identifies unreachable objects.
5. An unreachable object has no live references pointing to it.
6. After identifying unreachable objects, the GC reclaims their memory.
7. Garbage Collection runs automatically when the JVM decides it is needed.
8. You can request GC using [Link](), but it is only a suggestion to the JVM.
9. Developers should not rely on [Link]() for program logic.
10. Modern JVMs use advanced garbage collectors to improve performance.
11. Garbage Collection may briefly pause application execution.
12. Efficient object creation reduces GC overhead.
13. Setting a reference to null can make an object eligible for GC if no other references exist.
14. An object becoming eligible for GC does not mean it is removed immediately.
15. Garbage Collection is one of the reasons Java is considered memory-safe.

Example
public class GarbageCollectionExample {

public static void main(String[] args) {

Student s1 = new Student("Rakesh");

// Object becomes eligible for Garbage Collection


s1 = null;

[Link](); // Request to JVM (not guaranteed)

[Link]("Program continues...");
}
}

class Student {
String name;

Student(String name) {
[Link] = name;
}
}

Common Memory Errors


1. StackOverflowError

Occurs when the Stack Memory is exhausted, usually because of infinite recursion.

public class StackOverflowDemo {

static void test() {


test(); // Recursive call with no stopping condition
}

public static void main(String[] args) {


test();
}
}

2. OutOfMemoryError
Occurs when the Heap Memory cannot allocate more objects.

import [Link];
import [Link];

public class OutOfMemoryDemo {

public static void main(String[] args) {

List<byte[]> list = new ArrayList<>();

while (true) {
[Link](new byte[1024 * 1024]); // Continuously allocate 1 MB arrays
}
}
}

Complete Memory Flow


Program Starts


Class Loaded


Method Area Created


main() Called


Stack Frame Created


new Student()


Object Stored in Heap


Reference Stored in Stack


Method Ends


Stack Frame Removed


Object Becomes Unreachable


Garbage Collector Removes Object


Program Ends

Interview Questions

1. Where are objects stored in Java?


Objects and arrays are stored in Heap Memory.

2. Where are local variables stored?


Local variables and method parameters are stored in Stack Memory.

3. Where are static variables stored?


Static variables are stored in the Method Area.

4. What is Garbage Collection?


It is the automatic process of removing unreachable objects from Heap Memory to free space.

5. What is the difference between StackOverflowError and OutOfMemoryError?

StackOverflowError OutOfMemoryError
Stack becomes full Heap becomes full
Usually due to deep or infinite recursion Usually due to creating too many objects or insufficient heap space
Related to method calls Related to object allocation

🔷 Big Picture — Java Mein Memory Kaise Kaam Karta Hai?


Java mein tum khud memory allocate aur free nahi karte — yeh C/C++ se bilkul alag hai. Java ka JVM (Java Virtual
Machine) memory manage karta hai. JVM ke paas alag alag memory areas hain — har ek ka alag kaam hai. Sabse
important hain: Stack aur Heap.

Stack = Hotel registration desk — method call aaya, room mila (frame). Method khatam, room wapas (frame
popped). Heap = Shahar ka warehouse — sab objects yahan stored hain — jab tak koi reference rakhe, tab tak
safe. Koi reference nahi → GC le jaata hai!

☕ JVM Memory Architecture — Java Virtual Machine

📦 Heap 📚 Stack 🏛️Method Area 📌 PC Register 🔧 Native Stack


• Objects live • Method calls • Class • Program • Native method
here • Local variables metadata Counter calls (C/C++)
• new → yahan • Primitive • static variables • Points to next • JNI methods
aata values • static methods instruction • OS-level calls
• Young Gen • References • Bytecode • Per thread • Per thread
– Eden Space (not • Constants • Very small Native code
– Survivor 0,1 objects!) (aka Metaspace • Native:
• Old Gen • LIFO order in Java 8+) undefined
(Long-lived • Auto-cleanup Class-level data Thread's pointer
obj.) on return
• GC manages Thread-specific
this
Sabse bada area

📚 Stack Memory — Method Calls Ka Ghar


Stack memory thread-specific hoti hai — har thread ka apna stack hota hai. Jab bhi koi method call hota hai, ek
naya 'stack frame' push hota hai. Method return hone par frame automatically pop ho jaata hai. Stack LIFO (Last In
First Out) structure hai.

Stack = Hotel ka lift — sabse pehle andar aaya, sabse baad bahar jaayega. Method A ne method B ko call kiya
— B pehle return hoga, phir A. Jo baad mein aaya, woh pehle jaayega — LIFO!

2.1 — Stack Frame Mein Kya Hota Hai?


Har stack frame mein teen cheezein hoti hain: local variables, operand stack (calculations ke liye), aur frame data
(return address, exception table):

// Stack frames — what lives where


// Stack mein kya store hota hai — demo
public class StackDemo {

public static void main(String[] args) {


// Stack par: args reference (points to Heap)
// x = 10 (int — directly on stack)
int x = 10;

// s1 reference Stack par — actual Student object Heap par!


Student s1 = new Student("Rakesh", 20);

// Method call → naya Stack frame push hota hai


int result = calculate(5, 3);
[Link](result);
}

static int calculate(int a, int b) {


// Stack par: a=5, b=3, result=0 (sab local vars directly on stack)
int result = add(a, b);
return result;
}

static int add(int num1, int num2) {


// Stack par: num1=5, num2=3, sum=8
int sum = num1 + num2;
return sum; // ← Frame yahan destroy ho jaata hai
}
}

// Stack State jab add() chal raha hai:


// ┌─────────────────────────────┐ ← TOP
// │ add(): num1=5, num2=3, sum=8│
// ├─────────────────────────────┤
// │ calculate(): a=5, b=3, result│
// ├─────────────────────────────┤
// │ main(): x=10, s1=0xA100, args│
// └─────────────────────────────┘ ← BOTTOM

Stack ka Diagrammatic View:


⬆ add() returns → frame destroyed | calculate() returns → frame destroyed | main() last
add() frame ← TOP (active)
num1 = 5 (int)
num2 = 3 (int)
sum = 8 (int)

calculate() frame
result = 0 (int)
a = 5 (int)
b = 3 (int)

main() frame
s1 → 0xA100 (ref)
s2 → 0xA200 (ref)
x = 10 (int)

2.2 — StackOverflowError — Kab Hota Hai?


// StackOverflowError — cause and prevention
// StackOverflowError — Infinite recursion se Stack full ho jaata hai
public class StackOverflowDemo {
// ❌ Infinite recursion — base case nahi hai!
static int infiniteRecursion(int n) {
return infiniteRecursion(n + 1); // Stack frames badhte rahenge!
// Eventually: [Link]
}

// ✅ Correct recursion — base case zaroor hona chahiye


static int factorial(int n) {
if (n <= 1) return 1; // Base case — recursion ruk jaati hai
return n * factorial(n - 1); // Stack grows only up to n levels
}

// ✅ Iterative solution — Stack mein sirf ek frame


static int factorialIterative(int n) {
int result = 1;
for (int i = 2; i <= n; i++) result *= i; // No recursion = no extra frames
return result;
}

public static void main(String[] args) {


[Link](factorial(10)); // Works — 10 levels deep only
[Link](factorialIterative(10)); // Works — always 1 frame
// infiniteRecursion(0); // ← Exception mein mat daalna!
}
}

// JVM Stack size control:


// java -Xss2m MyClass → Stack size 2MB per thread (default ~512KB)
// java -Xss512k MyClass → 512KB per thread (smaller)

📦 Heap Memory — Objects Ka Warehouse


Heap Java ka sabse bada memory area hai — saare objects yahan store hote hain. new keyword se object create
hote hi Heap par jaata hai. JVM ka Garbage Collector (GC) Heap ko manage karta hai — unreachable objects ko
hataata hai.

Heap = Shahar ka bada warehouse. Har cheez (object) yahan rakhi hai. Stack mein sirf address card
(reference) hai — cheez yahan hai. Jab tak address card kisi ke paas hai, cheez safe. Address card fenk do
(null / out of scope) → GC warehouse se cheez hata dega!
3.1 — Stack vs Heap — Reference aur Object
// Stack vs Heap — primitives, references, and objects
// Stack vs Heap — Clearly samjho
public class HeapStackDemo {
public static void main(String[] args) {

// ── Primitives — directly on Stack ──


int age = 25; // Stack par: age = 25
double salary = 50000.0; // Stack par: salary = 50000.0
char grade = 'A'; // Stack par: grade = 'A'

// ── Objects — reference Stack par, object Heap par ──


String name = "Rakesh"; // name(Stack) → String obj(Heap)

int[] scores = {90, 85, 92}; // scores(Stack) → int[](Heap)

Student s1 = new Student("Priya", 22); // s1(Stack) → Student obj(Heap @ 0xA100)


Student s2 = s1; // s2(Stack) → SAME object on Heap @ 0xA100
Student s3 = new Student("Priya", 22); // s3(Stack) → NEW Student obj(Heap @ 0xA200)

[Link](s1 == s2); // true — same Heap address


[Link](s1 == s3); // false — different Heap addresses

// ── Memory picture ──
// STACK: HEAP:
// age = 25 [0xA100] Student{name='Priya', age=22}
// salary = 50000.0 [0xA200] Student{name='Priya', age=22}
// name → 0xH001 [0xH001] String{'Rakesh'}
// scores → 0xH002 [0xH002] int[]{90,85,92}
// s1 → 0xA100 ↑ s1 aur s2 dono yahan point karte hain
// s2 → 0xA100
// s3 → 0xA200

// s1 ko null karo — 0xA100 abhi bhi safe (s2 still holds reference)
s1 = null;
// 0xA100 GC eligible? NO — s2 abhi bhi reference rakh raha hai

s2 = null;
// 0xA100 GC eligible? YES — koi reference nahi! GC le jaayega
}
}

Feature 📚 Stack 📦 Heap


Stores Method frames, local vars, Objects, instance vars, arrays
primitives, references
Size Fixed, small (default ~512KB–1MB Large — entire free RAM available
per thread)
Speed Very fast (LIFO pointer movement) Slower (allocation + GC overhead)
Memory mgmt Automatic — frame pushed/popped Managed by Garbage Collector
Thread safety Thread-private — each thread has Shared — all threads access Heap
own stack
Error StackOverflowError (infinite OutOfMemoryError (too many
recursion) objects)
Lifetime Method duration — gone on return Until GC collects (no references)
References References stored here (point to Actual objects stored here
Heap)

3.2 — String Pool — Heap Ka Special Zone


// String Pool — Heap ka special zone
// String Pool — Heap mein special area hai strings ke liye

public class StringPoolDemo {


public static void main(String[] args) {

// String literal → String Pool se aata hai


String s1 = "Rakesh"; // Pool check karo — nahi tha → add karo
String s2 = "Rakesh"; // Pool check karo — already hai → same reference!
String s3 = "Priya"; // Pool mein naya entry

[Link](s1 == s2); // true — same Pool reference!


[Link](s1 == s3); // false — different pool entries

// new String() → ALWAYS new Heap object — Pool bypass!


String s4 = new String("Rakesh"); // New Heap object (NOT from pool)
String s5 = new String("Rakesh"); // Another new Heap object
[Link](s1 == s4); // false — pool vs heap
[Link](s4 == s5); // false — two different objects
[Link]([Link](s5)); // true — same content

// intern() — manually Pool mein daalo


String s6 = [Link](); // Pool reference return karta hai
[Link](s1 == s6); // true — s6 points to pool entry!

// MEMORY:
// String Pool (Heap ka part, Java 8+):
// "Rakesh" → 0xP001
// "Priya" → 0xP002
// s1 → 0xP001, s2 → 0xP001 (same!)
// s3 → 0xP002
// s4 → 0xH010 (new Heap object, NOT pool)
// s5 → 0xH011 (another new Heap object)
// s6 → 0xP001 (intern() returned pool reference)

// Best practice: literals use karo ("Rakesh") — not new String("Rakesh")


// Literals automatically pooled — memory efficient!
}
}

🔄 Object Life Cycle — Janam Se Mrityu Tak


Java mein ek object ka poora lifecycle 8 steps mein hota hai — class loading se lekar GC cleanup tak. Yeh
samajhna memory management aur performance optimization ke liye bahut zaroori hai.

# Phase What Happens Example


1 Class Loading JVM .class file load karta hai, [Link] → Metaspace
Method Area mein
2 Object Allocation new keyword → Heap (Eden) mein new Student(...)
memory allocate
3 IIB Execution Instance Init Block chalta hai — { logs = new ArrayList(); }
constructor se pehle
4 Constructor Run Constructor body execute — fields [Link] = name;
initialize
5 Object In Use References from Stack/fields point [Link](); [Link]();
to object on Heap
6 Unreachable Koi bhi live reference na bache → s = null; (or out of scope)
GC eligible
7 GC Collection Garbage Collector memory reclaim Minor GC / Major GC
karta hai
8 finalize() cleanup code — Java 9+ @Deprecated — don't rely
(deprecated) deprecated, avoid

// Object Lifecycle — Complete Demo (all 8 steps)


// Object Lifecycle — Step by step demo
class Student {
static int totalStudents = 0; // Method Area (Metaspace)
String name; // Heap (instance var)
int age; // Heap (instance var)
[Link]<String> courses; // Heap (reference on Heap)

// Step 3: IIB — constructor se pehle


{
courses = new [Link]<>(); // Heap par list create
totalStudents++;
[Link](" [IIB] Student #" + totalStudents + " initializing...");
}

// Step 4: Constructor
Student(String name, int age) {
[Link] = name;
[Link] = age;
[Link](" [Constructor] Student created: " + name);
}

void study(String course) {


[Link](course);
[Link](name + " ne " + course + " study kiya.");
}

@Override
public String toString() {
return "Student{" + name + ", age=" + age + ", courses=" + courses + "}";
}
}
public class Main {
public static void main(String[] args) {

// Step 1: Class loading (happens when JVM first encounters Student)


[Link]("=== Step 2-4: Object Creation ===");

// Step 2: new → Eden Space mein memory allocate


// Step 3: IIB runs
// Step 4: Constructor runs
Student s1 = new Student("Rakesh", 20); // s1 reference Stack par
Student s2 = new Student("Priya", 22); // s2 reference Stack par

[Link]("\n=== Step 5: Object In Use ===");


[Link]("Java");
[Link]("Python");
[Link]("Data Science");
[Link](s1);
[Link](s2);
[Link]("Total students: " + [Link]);

[Link]("\n=== Step 6: Making Objects Unreachable ===");

// s1 = null → 0xA100 par Student object GC eligible ho gaya


s1 = null;
[Link]("s1 = null → s1's Student is GC eligible!");

// s2 scope se bahar jaayega jab main() ends

[Link]("\n=== Step 7: Suggest GC (no guarantee!) ===");


[Link](); // Suggest karna — guarantee nahi!
[Link]("GC suggested. JVM apni marzi se chalaayega.");

// s2 abhi bhi reachable hai — safe hai


[Link]("s2 still alive: " + [Link]);

} // main() ends → s2 bhi unreachable → GC eligible


}
🗑️Garbage Collection — JVM Ka Safaai Waala
Garbage Collection (GC) Java ki ek magical feature hai — tum manually memory free nahi karte. JVM ka GC
automatically unreachable objects dhundta hai aur unki memory reclaim karta hai. Lekin GC kaise kaam karta hai
— yeh jaanna important hai!

GC = Municipality ka safai truck. Ghar (Heap) mein jo cheezein hain — agar unka koi address nahi, koi claim
nahi → truck uthaa le jaata hai. Uthaaane ka time uncertain hai — '[Link]()' sirf request hai, guarantee
nahi!

5.1 — Generational GC — Young aur Old Generation


Java GC 'Generational Hypothesis' par based hai: 'Zyaadatar objects jaldi mar jaate hain.' Eden mein paida hote
hain — agar survive karo toh Survivor, phir Old Gen. Old Gen ke objects bahut kam aur bahut slow GC mein jaate
hain:

Generation What Lives Here GC Type Frequency


Eden Space Naye objects — new se Minor GC Very frequent (fast)
aate hain
Survivor S0/S1 Minor GC survive kiye Minor GC Frequent — between S0
objects ↔ S1
Old Generation Long-lived objects (age Major GC Infrequent (slow — STW)
threshold)
Metaspace (Java Class metadata, static data Full GC Rare
8+)

// GC Generations + Tuning flags + Heap monitoring


// GC Generations — Objects ka journey

// Eden Space — naye objects yahan aate hain


String temp = "I am a temp string"; // Eden mein born
// Minor GC aata hai — temp unreachable hai → collected!
// (Method ends, koi reference nahi)

// Long-lived object — Old Gen tak pahunchta hai


class AppConfig {
static final AppConfig INSTANCE = new AppConfig(); // Static → Old Gen mein jaata hai
String dbUrl = "jdbc:mysql://localhost/mydb";
int maxConnections = 100;
// Yeh object application lifetime tak jeeyega
}

// GC tuning flags — JVM options


// java -Xms256m -Xmx1g MyApp
// -Xms = Initial Heap size (256 MB)
// -Xmx = Maximum Heap size (1 GB)

// java -XX:+UseG1GC MyApp → G1 GC (default Java 9+)


// java -XX:+UseZGC MyApp → ZGC (low latency, Java 15+)
// java -XX:+UseParallelGC MyApp → Parallel GC (throughput)

// Check heap usage programmatically


public class HeapMonitor {
public static void main(String[] args) {
Runtime runtime = [Link]();

long totalMemory = [Link](); // Current heap size


long freeMemory = [Link](); // Free in current heap
long maxMemory = [Link](); // -Xmx value
long usedMemory = totalMemory - freeMemory;

[Link]("Total : %,d bytes (%.1f MB)%n", totalMemory, totalMemory/1e6);


[Link]("Free : %,d bytes (%.1f MB)%n", freeMemory, freeMemory/1e6);
[Link]("Max : %,d bytes (%.1f MB)%n", maxMemory, maxMemory/1e6);
[Link]("Used : %,d bytes (%.1f MB)%n", usedMemory, usedMemory/1e6);
}
}

5.2 — GC Roots — Objects Kab Reachable Hote Hain?


// GC Roots — Reachability aur circular references
// GC Roots — Kaunse objects DEFINITELY alive hain?

// GC Root types:
// 1. Active threads ke Stack variables
// 2. Static variables in loaded classes
// 3. JNI references
// 4. System class loader references

// Reachability demo:
public class ReachabilityDemo {
static Student staticStudent; // Static var → GC Root → always reachable

public static void main(String[] args) {

Student s1 = new Student("Rakesh", 20); // Stack var → GC Root


Student s2 = new Student("Priya", 22); // Stack var → GC Root
Student s3 = new Student("Ajay", 21); // Stack var → GC Root

staticStudent = s1; // Static var bhi s1 ko point kar raha hai

// Scenario 1: s2 = null
s2 = null;
// s2 ka Student: koi GC Root tak path nahi → ELIGIBLE for GC

// Scenario 2: s1 = null
s1 = null;
// s1 ka Student: staticStudent ABHI BHI point kar raha hai!
// → NOT eligible — staticStudent GC Root hai

// Scenario 3: static reference bhi clear karo


staticStudent = null;
// Ab s1 wala Student: koi GC Root path nahi → ELIGIBLE

// Circular references — GC smart hai!


Student a = new Student("A", 20);
Student b = new Student("B", 21);
// [Link] = b; // (assume Student has a friend field)
// [Link] = a;
a = null;
b = null;
// a aur b ek doosre ko point karte hain — lekin koi GC Root nahi!
// Modern GC (Mark-and-Sweep) yeh bhi collect karta hai ✅
}
}

🔗 Java Reference Types — Strong, Weak, Soft, Phantom


Java mein 4 types ke references hain — GC unhe alag tarike se treat karta hai. Yeh advanced concept hai jo
caching, memory-sensitive applications mein use hota hai:
Type Class GC Behavior Use Case
Strong Reference Default (Student s = new) Never GC unless Normal usage
unreachable
Soft Reference SoftReference<T> GC only when memory Image/object cache
LOW
Weak Reference WeakReference<T> GC anytime next cycle Canonical maps,
listeners
Phantom PhantomReference<T> After finalization — Resource cleanup, off-
Reference cleanup hook heap

// WeakReference aur SoftReference — practical demo


// Weak Reference — practical example
import [Link].*;

public class WeakRefDemo {


public static void main(String[] args) {

// Strong reference
Student strong = new Student("Rakesh", 20);

// WeakReference — GC anytime collect kar sakta hai


WeakReference<Student> weakRef = new WeakReference<>(strong);

[Link]("Before null: " + [Link]()); // Student object

// Strong reference remove karo


strong = null;

// GC suggest karo
[Link]();

// Ab [Link]() null return kar sakta hai


Student fetched = [Link]();
if (fetched != null) {
[Link]("Still alive: " + [Link]);
} else {
[Link]("GC ne collect kar liya! [Link]() = null");
}

// SoftReference — memory pressure par collect hota hai


SoftReference<byte[]> cache = new SoftReference<>(new byte[1024 * 1024]); // 1MB
// Jab Heap almost full ho → GC ise collect karega
// Normal condition mein yeh survive karega
byte[] data = [Link]();
if (data != null) [Link]("Cache hit: " + [Link] + " bytes");
else [Link]("Cache miss: GC ne collect kiya");
}
}

⚠️Memory Leaks in Java — GC bhi Nahi Bachaa Sakta!


Log samajhte hain Java mein memory leak nahi hoti — kyunki GC hai. Yeh galat hai! Java mein bhi memory leak
ho sakti hai — jab objects Heap par hain lekin use nahi ho rahe, par unka reference exist karta hai. GC unhe collect
nahi kar sakta!

// Memory Leaks — 4 Common Patterns aur Fixes


// Memory Leaks — 4 Common Patterns in Java

// ── LEAK 1: Static collection mein continuously add karna ──


import [Link].*;

class LeakDemo1 {
// ❌ LEAK: Static list — JVM life tak rahega, objects kabhi collect nahi honge
static List<byte[]> memoryHog = new ArrayList<>();

static void addData() {


[Link](new byte[1024 * 1024]); // 1MB har call mein add!
// yeh list kabhi clear nahi hoti → OutOfMemoryError eventually
}

// ✅ FIX: Limit size ya clear karo


static final int MAX_SIZE = 100;
static List<byte[]> fixedList = new ArrayList<>();

static void addDataFixed(byte[] data) {


if ([Link]() >= MAX_SIZE) {
[Link](); // Ya LRU eviction use karo
}
[Link](data);
}
}

// ── LEAK 2: Listeners / Callbacks register karo, remove nahi karo ──


class EventSystem {
static List<Runnable> listeners = new ArrayList<>();

// ❌ LEAK: Listeners add hote hain, kabhi remove nahi hote


static void addListener(Runnable r) { [Link](r); }

// ✅ FIX: removeListener() bhi honi chahiye — aur callers se call karwaao


static void removeListener(Runnable r) { [Link](r); }
}

// ── LEAK 3: HashMap mein hashCode/equals sahi nahi hai ──


class BadKey {
String id;
BadKey(String id) { [Link] = id; }
// hashCode/equals override NAHI kiya!
}

class LeakDemo3 {
static Map<BadKey, String> map = new HashMap<>();

static void badMapUsage() {


for (int i = 0; i < 10000; i++) {
// ❌ LEAK: Har iteration mein new BadKey("same") → different hash
// Map mein 10000 DUPLICATE entries — phir bhi GC collect nahi kar sakta
[Link](new BadKey("user_" + i), "data_" + i);
}
// Map clear nahi hota — saare objects alive hain
}
}

// ── LEAK 4: try-with-resources nahi use kiya ──


import [Link].*;

class LeakDemo4 {
// ❌ LEAK: InputStream kabhi close nahi hota — file handle leak!
static void badRead(String path) throws IOException {
InputStream is = new FileInputStream(path);
int data = [Link]();
// Agar exception aaya → [Link]() kabhi nahi chala!
}

// ✅ FIX: try-with-resources — automatically closes


static void goodRead(String path) throws IOException {
try (InputStream is = new FileInputStream(path)) {
int data = [Link]();
// [Link]() automatically called — even on exception!
}
}
}

// Memory Leak Fix Checklist:


// ✅ Static collections mein size limit lagao / clear karo
// ✅ Listeners/Callbacks ko remove karo jab zaroorat na ho
// ✅ equals() aur hashCode() override karo Map/Set keys ke liye
// ✅ Resources (Streams, DB connections) try-with-resources mein rakho
// ✅ WeakReference use karo caches ke liye (SoftReference better for caches)
// ✅ Profiling tools: VisualVM, JProfiler, Eclipse MAT use karo

✅ Memory Best Practices — Production-Ready Code

// Memory Best Practices — Production checklist


// Memory Best Practices — Ek Jagah Sab Kuch

// 1. ✅ Objects ko local scope mein rakho (method level)


void process() {
BigObject b = new BigObject(); // Method ke andar — method ends → GC eligible
[Link]();
} // b unreachable here — good!

// 2. ✅ Unnecessary object creation avoid karo — StringBuilder use karo


// ❌ String concatenation in loop — N new String objects banta hai!
String bad = "";
for(int i=0; i<1000; i++) bad += i; // 1000 temp String objects!

// ✅ StringBuilder — ek hi mutable object


StringBuilder sb = new StringBuilder();
for(int i=0; i<1000; i++) [Link](i); // Sirf ek object
String result = [Link]();

// 3. ✅ Collections ki initial capacity set karo


List<String> list = new ArrayList<>(1000); // 1000 elements expected — resize avoid
Map<String,String> map = new HashMap<>(16, 0.75f); // Initial capacity + load factor

// 4. ✅ try-with-resources — ALWAYS for closeable resources


try (Connection conn = [Link](url);
PreparedStatement ps = [Link](sql)) {
// Use conn and ps
[Link]();
} // Both auto-closed here — even on exception ✅

// 5. ✅ Heap monitoring — production mein


Runtime rt = [Link]();
long usedMB = ([Link]() - [Link]()) / (1024*1024);
if (usedMB > 800) [Link]("WARNING: High memory usage: " + usedMB + "MB");

// 6. ✅ JVM flags — production settings


// java -Xms512m -Xmx2g // Min 512MB, Max 2GB heap
// java -XX:+UseG1GC // G1 GC — balanced throughput+latency
// java -XX:MaxGCPauseMillis=200 // Target max GC pause 200ms
// java -XX:+HeapDumpOnOutOfMemoryError // OOM par heap dump lo — analyze karo
// java -verbose:gc // GC logs print karo — debug ke liye

📋 Quick Revision — Exam aur Interview ke Liye

Sabse Important Points


• Stack: method frames, local variables, primitives — thread-private, auto-cleanup on return
• Heap: all objects, instance vars, arrays — shared, GC manages — sabse bada area
• Method Area: class metadata, static vars, bytecode — Metaspace (Java 8+)
• Stack stores reference: object Heap par, reference Stack par — dono alag jagah
• new keyword: Eden Space (Young Gen) mein object allocate karta hai
• GC eligible: jab koi bhi GC Root se path na bache — null ya out of scope
• Minor GC: Eden → Survivor — fast, frequent, young gen
• Major/Full GC: Old Gen — slow, Stop-The-World pause, infrequent
• String Pool: Heap ka special area — literals share hote hain; new String() → bypass
• StackOverflowError: infinite recursion — stack frames khatam ho jaate hain
• OutOfMemoryError: Heap full — GC bhi help nahi kar sakta
• Memory leak: object reachable hai par use nahi ho raha — static collection main pattern
• WeakReference: GC anytime collect kar sakta hai — cache ke liye useful
• try-with-resources: resources hamesha close honge — even on exception

Topic Key Rule Hinglish Yaad-Sutra


Stack Method frames + local vars Register karo hotel mein — check out par khali
Heap All objects live here Warehouse — saara saman yahan, reference
slip stack par
new keyword Eden (young gen) mein Naya ghar liya — Eden colony mein!
allocate
Reference Stack mein — object Heap Address card pocket mein — ghar Heap mein
mein
null = eligible No reference = GC eligible Koi dost nahi dhundhne wala — safai waala le
jayega
Minor GC Eden → Survivor → Old Gen Bachcha school se college, phir naukri
Major / Full GC Old Gen cleanup — STW Bada safai — poora kaam ruka, phir sab theek
pause
StackOverflow Infinite recursion — stack full Hotel mein infinite rooms book kiye — capacity
khatam!
OutOfMemory Heap full — GC bhi help na kar Warehouse full — aur jagah nahi
sake
WeakReference GC can collect anytime Dost ka ghar — agar GC aaye, chala jaayega

Java Programming Notes — Memory Management • Heap • Stack • Garbage Collection • Object Life Cycle •
Memory Leaks | Hinglish Edition 🇮🇳

You might also like