Skip to content
QuizMaker logoQuizMaker
Activity
Java Programming: From Zero to Enterprise
4. Advanced Java & Frameworks
1. Getting Started with Java & the JVM
2. Data Types & Variables
3. Control Flow: Ifs & Loops
4. String Manipulation in Depth
5. Methods (Functions) Architecture
6. Arrays & The Enhanced For Loop
7. User Input via Scanner
8. Mathematical Operations & The Math Class
9. Operators in Depth
10. Block Scope & Variable Lifecycles
11. Introduction to Object-Oriented Programming
12. Classes & Instances Deep Dive
13. Constructors
14. Encapsulation & The 'this' Keyword
15. Inheritance: Extending Functionality
16. Polymorphism & Method Overriding
17. Abstraction & Abstract Classes
18. Interfaces: The Ultimate Contract
19. Packages & Access Modifiers
20. Enums (Enumerations)
21. Exceptions: Handling Runtime Errors
22. The 'throw' and 'throws' keywords
23. Dates, Times, and Formatting
24. Enumerable Data Structures
25. LinkedLists: The Alternative
26. HashMaps: Key-Value Architecture
27. HashSets: The Art of Uniqueness
28. Iterator: Safe Collection Traversal
29. Wrapper Classes & Autoboxing
30. Basic File I/O
31. Generics: Type-Safe Templates
32. Lambda Expressions & Functional Interfaces
33. The Stream API: Functional Data Pipelines
34. Optional: Beating the NullPointerException
35. Multithreading & Concurrency Basics
36. JDBC: Connecting to SQL Databases
37. Annotations & Reflection
38. The JVM Garbage Collector
39. Introduction to Spring Boot
40. Unit Testing with JUnit
41. Java Collections for DSA
CONTENTS

38. The JVM Garbage Collector

How Java cleans up your memory messes automatically.

Feb 22, 20264 views0 likes0 fires
18px

[!NOTE] In legacy C/C++, if you allocated memory for 10,000 Car objects, it was your explicit responsibility to order the CPU to free() that memory when you finished. If you forgot, the RAM filled up endlessly until the computer suffered a Blue Screen of Death. This is called a "Memory Leak".

Java completely automated this with the Garbage Collector (GC), heavily influencing the design of C# and Go.

The Heap Memory

Every time you execute the new keyword (e.g., new Car()), Java allocates physical space in an area of RAM called the Heap.

public void processOrders() {
    // 1. Spawns an object on the massive Heap. 
    // The 'report' variable on the Stack is just a pointer pointing to the Heap object!
    OrderReport report = new OrderReport(); 
    report.compile();
} // 2. Method ends. The 'report' pointer is destroyed.

When the method finishes, the report pointer is destroyed. But the massive OrderReport object is still sitting entirely intact out on the Heap, consuming megabytes of RAM!

The Tracing Garbage Collector

Because no active variables are currently pointing to that OrderReport object, it is officially orphaned. It is impossible for your code to ever access it again.

A daemon thread called the Garbage Collector sleeps in the background. Periodically, it wakes up and pauses the application.

  1. Mark Phase: It traces every single active variable in your program, painting the objects they point to as "Alive".
  2. Sweep Phase: It scans the entire Heap array. Any orphaned object that the Mark phase didn't paint is annihilated. The RAM is recovered!

The Risk of Memory Leaks in Java

Wait, if Java automatically sweeps orphaned objects, how can a Java Server suffer a Memory Leak?

If you maintain a massive static (global) ArrayList, and endlessly add items to it, they are technically never orphaned.

public class Cache {
    // A single global list
    public static ArrayList<User> staticUserCache = new ArrayList<>();
    
    public void loginUser() {
        // We endlessly add users, but NEVER call .remove()
        staticUserCache.add(new User()); 
    }
}

Because the staticUserCache variable is permanently alive (it's attached to the Class itself), the millions of User objects inside it are never considered "orphaned". The Garbage Collector refuses to touch them. Eventually, your JVM crashes with a catastrophic OutOfMemoryError.

Share this article

Share on TwitterShare on LinkedInShare on FacebookShare on WhatsAppShare on Email

Test your knowledge

Take a quick quiz based on this chapter.

mediumJava
Quiz: Garbage Collection
2 questions5 min

Continue Learning

39. Introduction to Spring Boot

Advanced
12 min

40. Unit Testing with JUnit

Advanced
14 min

41. Java Collections for DSA

Advanced
22 min
Lesson 8 of 11 in 4. Advanced Java & Frameworks
Previous in 4. Advanced Java & Frameworks
37. Annotations & Reflection
Next in 4. Advanced Java & Frameworks
39. Introduction to Spring Boot
← Back to Java Programming: From Zero to Enterprise
Back to Java Programming: From Zero to EnterpriseAll Categories