HOW GARBAGE COLLECTOR WORKS IN JAVA Garbage Collection (GC) in Java is an automatic memory management mechanism provided by the JVM. Its primary role is to free heap memory by removing objects that are no longer used by the application. GC works only on Heap memory; Stack memory is cleared automatically when a method execution ends. The golden rule of Garbage Collection is simple: An object becomes eligible for GC only when it is unreachable. Reachable objects are not collected, while unreachable objects are eligible for collection. Garbage Collection starts from special references known as GC Roots. Instead of scanning the entire heap, the Garbage Collector begins traversal from these roots. GC Roots include local variables in the stack, active threads, static variables, and JNI references. Using reachability analysis, GC determines which objects can be accessed directly or indirectly from GC Roots. Reachable objects are considered alive, while unreachable objects are treated as garbage. Garbage Collection typically works in three phases. In the Mark phase, the Garbage Collector traverses objects starting from GC Roots and marks all reachable objects as alive. No memory is freed during this phase. In the Sweep phase, all unmarked (dead) objects are removed and their memory is freed. A drawback of this phase is memory fragmentation. In the Compact phase, live objects are moved together to eliminate fragmentation, creating continuous free memory and improving allocation performance. The JVM uses Generational Garbage Collection because most objects have a short lifespan. Heap memory is divided into Young Generation (Eden and Survivor spaces) and Old Generation for long-living objects. When an object is created, it is allocated in Eden space. If it survives Minor GC, it moves to Survivor space. After surviving multiple GC cycles, it is promoted to Old Generation. Minor GC occurs when Eden space is full and is fast and frequent. Major or Full GC occurs when Old Generation becomes full and causes Stop-The-World pauses, where all application threads are temporarily paused. Different Garbage Collectors include Serial GC, Parallel GC, CMS (deprecated), and G1 GC. G1 GC is widely used in enterprise applications due to its predictable pause times and better performance on large heaps. #Java #CoreJava #JVM #GarbageCollection #JavaDeveloper #BackendDevelopment #TechLearning #JavaMemory #JVMInternals #SoftwareEngineering #Programming #InterviewPreparation #ComputerScience #Coding
Java Garbage Collection: How it Works
More Relevant Posts
-
Java Fundamentals Series – Day 5 Garbage Collection in Java : In Java, developers do not need to manually free memory. JVM automatically manages memory using Garbage Collection (GC). The Garbage Collector is an Mechanism were default implemented inside JVM which is Invoke automatically In java there has a method gC() which is present inside the System Class this gC() method is a static method so there is no need for object to invoke this method so we can able to access this particular method by the class name *** System.gC() ***. By help of this method we just provide the request to JVM to call the ** Garbage Collector ** but we cannot assure that it may or may not be call the GC . It is totally depends on JVM here we just provide request. What is Garbage Collection? Garbage Collection is the process of automatically removing unused objects from Heap memory. Why GC is Important? 1 Prevents memory leaks 2 Frees unused memory 3 Improves application performance How GC Works? 1 JVM identifies objects that are no longer referenced 2 These objects become eligible for garbage collection 3 GC reclaims the memory occupied by them 4 It removes the memory for anonymous. object Method : void finalize(): Incase we needed to do some set of work before GC get Called in that particular time we can use this finalize () this method is defined as protected for example - closing the file this like operation.we can able to provide inside this finalize() method #Java #GarbageCollection #JVM #BackendDeveloper #Placements
To view or add a comment, sign in
-
🧵Threads: Where Java Concurrency Begins In the last post we discussed about concurrency.Today let's start with the foundation: Threads A java thread is the smallest execution of a program.It is a subprocess that runs independently but shares the same memory space with other threads. 👨💻 Creating and Running threads The Java Standard Library provides two primary ways to work with threads: by extending the Thread class or implementing the Runnable interface. 👉Extending the Thread class: class MyThread extends Thread { @Override public void run() { // Code that runs in the new thread System.out.println("The thread is running."); } } public class ThreadExample { public static void main(String[] args) { MyThread myThread = new MyThread(); myThread.start(); // Start the thread } } ⚠️ Key Points: 🔸Extend the Thread class 🔸Override the run() method 🔸Call start() to begin execution 👉 Implementing the Runnable Interface: class MyRunnable implements Runnable { @Override public void run() { // Code that will run in the new thread System.out.println("The thread is running."); } } public class RunnableExample { public static void main(String[] args) { Thread thread = new Thread(new MyRunnable()); thread.start(); // Start the thread } } ⚠️Key Points: 🔸Implement Runnable interface 🔸Allows class inheritance 🔸Same task can be reused by multiple threads. 🧠Important Always call the start() method instead of run(). The start() method creates a new thread and executes the task, while run() executes the task in the current thread. 🧐 Ignoring this detail would cause hindrance in achieving our objective(concurrency). #Java #Threads #Concurrency #Parallelism #SoftwareEngineering #Backend #Programming
To view or add a comment, sign in
-
-
Day 4 of 10 – Core Java Recap: Looping Statements & Comments 🌟 Continuing my 10-day Java revision journey 🚀 Today I revised Looping Concepts and Comments in Java. 🔁 1️⃣ Looping Statements in Java Looping statements are used to execute a block of code repeatedly based on a condition. 📌 Types of loops: ✔ for loop Used when the number of iterations is known. Syntax: for(initialization; condition; updation) { // statements } ✔ while loop Checks condition first, then executes. Syntax: while(condition) { // statements } ✔ do-while loop Executes at least once, then checks condition. Syntax: do { // statements } while(condition); ✔ for-each loop (Enhanced for loop) Used to iterate over arrays and collections. Syntax: for(dataType variable : arrayName) { // statements } 🔹 Nested Loops A loop inside another loop Commonly used for patterns and matrix problems ⛔ break and continue ✔ break → Terminates the loop completely ✔ continue → Skips current iteration and moves to next iteration 📝 2️⃣ Comments in Java Comments are used to provide extra information or explanation in the code. They are not executed by the compiler. 📌 Types of Comments: ✔ Single-line comment // This is a single-line comment ✔ Multi-line comment /* This is a multi-line comment */ ✔ Documentation Comment (Javadoc) /** Documentation comment */ Used to generate documentation Applied at class level, method level Helps describe package, class, variables, and methods 📌 Common Documentation Tags: @author @version @param @return @since 💡 Key Learnings Today: Understood how loops control program flow Learned the difference between for, while, and do-while Practiced nested loops Understood the importance of proper code documentation Building strong fundamentals step by step 💻🔥 #Java #CoreJava #Programming #JavaDeveloper #CodingJourney #Learning
To view or add a comment, sign in
-
ArrayList ✈️ In Java, an ArrayList is a member of the Java Collections Framework and resides in the java.util package. While a standard Java array (e.g., int[]) is fixed in length, an ArrayList is a resizable-array implementation of the List interface. How It Works: The "Growing" Mechanism When you add an element to an ArrayList, Java checks if there is enough room in the underlying memory. If the internal array is full, the ArrayList performs the following: It allocates a new, larger array ✅Key Features in Java Type Safety: It uses Generics, allowing you to specify what type of data it holds (e.g., ArrayList<String>). Wrapper Classes: It cannot store primitive types (like int, double, char) directly. Instead, Java uses "Autoboxing" to convert them into objects (like Integer, Double, Character). Nulls and Duplicates: It allows you to store duplicate elements and null values. Unsynchronized: By default, it is not thread-safe. If multiple threads access it simultaneously, you must handle synchronization manually. It copies all existing elements to the new array. It updates its internal reference to this new array. ✅ArrayList vs. LinkedList A common interview question is when to use ArrayList over LinkedList. ArrayList: Best for frequent access and storing data where you mostly add/remove from the end. LinkedList: Best if you are constantly inserting or deleting items from the beginning or middle of the list. Would you like me to explain the specific differences between ArrayList and Vector, or perhaps show you how to sort an ArrayList using Collections.sort(). Huge thanks for the mentorship on Java ArrayList Anand Kumar Buddarapu Saketh Kallepu Uppugundla Sairam #ArrayList #Java #DataStructures #Programming #Coding #SoftwareEngineering #Backend #JavaDeveloper #Algorithms #TechTips #ComputerScience
To view or add a comment, sign in
-
“var” in Java: less noise… or less clarity? Local Variable Type Inference (LVTI) has been in Java since JDK 10, and it’s one of those features that can either make code beautifully readable—or quietly introduce ambiguity. In this article, Simon Ritter breaks down when `var` is a *friend*: ✅ the initializer makes the type obvious ✅ it helps split long / chained expressions into readable steps ✅ it reduces repetition without hiding intent …and when it becomes a *foe*: ⚠️ the type isn’t obvious without an IDE ⚠️ literals/generics inference can surprise you ⚠️ overloads and subtle type changes can alter behavior later My takeaway: `var` is a readability tool, not a typing shortcut. Use it where local reasoning still works. #Java #OpenJDK #SoftwareEngineering #CleanCode #DeveloperProductivity
To view or add a comment, sign in
-
Understanding Map in Java — One of the Most Important Concepts in the Collections Framework The Map interface in Java is a powerful data structure used to store data in key–value pairs, where every key is unique and maps to a specific value. Let’s simplify it: Key Characteristics: - Stores data as Key → Value pairs - Keys must be unique (duplicate keys overwrite values) - Duplicate values are allowed - No indexing — access data using keys Common Map Implementations: - HashMap → Fastest performance (O(1)), no order guarantee - LinkedHashMap → Maintains insertion order - TreeMap → Sorted keys (O(log n)) - ConcurrentHashMap → Thread-safe for multi-threaded applications Most Used Methods: - put() – Add or update data - get() – Retrieve value - remove() – Delete entry - containsKey() – Check key existence - entrySet() – Iterate key-value pairs Interview Tip: - If ordering matters → use LinkedHashMap - If sorting is needed → use TreeMap - If performance matters → use HashMap Java Collections become much easier once you truly understand how Map works. What Map implementation do you use most in your projects #Java #JavaDeveloper #SpringBoot #BackendDevelopment #JavaCollections #Programming #SoftwareDevelopment #Coding #TechLearning
To view or add a comment, sign in
-
-
Struggling with Java fundamentals? 🚀 In a recent tech discussion, we broke down some core concepts that every Java developer should have on lock. If you’re preparing for an interview or just brushing up, here is the cheat sheet: 1. Comparing Enum Values Always use == for enums. Since enums are singletons, == checks reference equality, is null-safe, and is compile-time checked. Using .equals() is safe but unnecessary here. 2. The this Keyword It refers to the current object instance. Use it to: · Distinguish instance variables from parameters (this.name = name). · Call another constructor of the same class (this()). · Pass the current object as a parameter to another method. 3. final Keyword in Inheritance · final Class: Cannot be subclassed (e.g., String). · final Method: Cannot be overridden by a subclass (prevents behavior change). · final Variable: Cannot be reassigned (makes it a constant). 4. Wrapper Classes & Autoboxing · Wrapper: Objects that encapsulate primitives (e.g., Integer for int). · Autoboxing: Automatic conversion int → Integer when needed. · Unboxing: Automatic conversion Integer → int. Gotcha: Comparing Integer objects with == for values >127 can fail due to caching! 5. Varargs (Variable Arguments) Allows passing an arbitrary number of arguments to a method. · Benefit: Cleaner syntax, no need to explicitly create an array. · Limitation: Must be the last parameter in the method signature. Overloading with varargs can be tricky and lead to ambiguity. 💬 Test Your Knowledge: Q1: Why is it better to use == for enums instead of .equals()? Q2: If a class is marked final, can you still create an instance of it? Q3: What is the output of System.out.println(new Integer(50) == new Integer(50));? (Hint: Think object reference vs value!) Drop your answers in the comments! 👇 #Java #Programming #TechInterview #SoftwareDevelopment #CodingTips
To view or add a comment, sign in
-
Java. Did you know? Did you know that Java has a "ghost" variable lurking in every nested class? It’s invisible, it’s final, and it could be silently keeping objects alive when you least expect it. When you create an inner class (a non-static nested class), the Java compiler secretly adds a hidden instance field: this$0. This field holds a reference to the outer class instance that created it. You never see it in your code, but it's always there—quietly ensuring the inner class can access the outer class's members. Here’s where it gets spooky: If you pass an instance of that inner class to somewhere else (like an event handler, a callback, or a collection), you're also passing an invisible chain link to the outer object. This is a classic source of memory leaks in Android and desktop applications. Even if you null out all your visible references to the outer class, that hidden this$0 in the inner class can keep the entire outer object alive for garbage collection. Worst part? Most profilers won't show it as a named field - you'll just see mysterious retention chains and wonder why your objects refuse to die. It’s the ghost in the Java machine. #Java #Programming #SoftwareEngineering #TechTips #CodeNewbie #JavaDevelopers #MemoryManagement #Coding #DeveloperLife #TechFacts
To view or add a comment, sign in
-
-
Day 40 – Java 2026: Smart, Stable & Still the Future Topic: Object in Java (Core of OOP) What is an Object? An object is a runtime instance of a class that represents a real-world entity. It contains: • State (variables) • Behavior (methods) • Identity (unique memory location) Steps to Create an Object Declare a reference variable Create an object using the new keyword Assign object to reference Student s1 = new Student(); Reference Variable A reference variable stores the memory address of an object, not the actual object. It is used to access the object. Example: s1 → reference variable new Student() → object Declaration and Initialization Declaration only Student s1; Initialization only s1 = new Student(); Declaration + Initialization Student s1 = new Student(); Object vs Reference Variable FeatureObjectReference VariableMemory LocationHeapStackStoresActual dataAddress of objectCreated Usingnew keywordClass typeExamplenew Student()s1Key Points • One class can create multiple objects • Each object has separate memory • Reference variable points to object • Objects are created at runtime • Java programs work using objects Simple Example class Student { String name; } public class Main { public static void main(String[] args) { Student s1 = new Student(); s1.name = "Sneha"; System.out.println(s1.name); } } Key Takeaway: Object = Real entity Reference = Way to access that entity #Java #40 #OOP #LearnJava #JavaDeveloper #Programming #100DaysOfCode #CareerGrowth
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development