📖 New Post: Java Memory Model Demystified: Stack vs. Heap Where do your variables live? We explain the Stack, the Heap, and the Garbage Collector in simple terms. #java #jvm #memorymanagement
Java Stack vs Heap Memory Model Explained
More Relevant Posts
-
After understanding how Java code gets executed, the next question is: Where does the data actually get stored? In JVM, memory is mainly divided into two parts: Heap Memory: - Used to store objects and class instances - Shared across all threads - Managed by Garbage Collection - Objects generally have a longer lifetime Stack Memory: - Stores method calls and local variables - Each thread has its own stack - Automatically managed - Data exists only during method execution Key difference: Heap → Stores Objects Stack → Handles Execution (methods & variables) Understanding this difference helps in writing better and more efficient Java applications. #Java #JVM #BackendDevelopment #Learning
To view or add a comment, sign in
-
-
#Day02 After understanding how Java code gets executed, the next question is: 👉 Where does the data actually get stored? In JVM, memory is mainly divided into two parts: 🔹 Heap Memory • Used to store objects and class instances • Shared across all threads • Managed by Garbage Collection • Objects generally have longer lifetime 🔹 Stack Memory • Stores method calls and local variables • Each thread has its own stack • Automatically managed • Data exists only during method execution 📌 Key difference: Heap → Stores Objects Stack → Handles Execution (methods & variables) Understanding this difference helps in writing better and more efficient Java applications. #Java #JVM #BackendDevelopment #Learning
To view or add a comment, sign in
-
-
Something small… but it changed how I think about Java performance. We often assume `substring()` is cheap. Just a slice of the original string… right? That was true **once**. 👉 In older Java versions, `substring()` shared the same internal char array. Fast… but risky — a tiny substring could keep a huge string alive in memory. 👉 In modern Java, things changed. `substring()` now creates a **new String with its own memory**. Same value ❌ Same reference ❌ Safer memory ✅ And this is where the real learning hit me: **Understanding behavior > memorizing APIs** Because in a real system: * Frequent substring operations = more objects * More objects = more GC pressure * More GC = performance impact So the question is not: “Do I know substring?” But: “Do I know what it costs at runtime?” That shift — from syntax to system thinking — is where growth actually starts. #Java #BackendEngineering #Performance #JVM #LearningJourney
To view or add a comment, sign in
-
Day 46-What I Learned In a Day(JAVA) Today I explored the execution of a Java program and understood how it works inside the JVM: JVM Memory Structure: • Method Area Stores class-level data like methods, static variables, and metadata • Class (Static) Area Holds static variables and static initializers • Stack Area Manages method calls, local variables, and execution flow • Heap Area Stores objects and instance variables Execution Order of Java Program: 1️⃣ Class is loaded into Method Area 2️⃣ Static variables & static initializers are executed (Class Area) 3️⃣ Main method is pushed into Stack Area 4️⃣ Objects are created in Heap Area (if any) 5️⃣ Methods execute using Stack (LIFO order) Program Components: • Methods -Define program behavior • Variables -Store data (local, instance, static) • Static Initializers -Execute once when the class loads #Java #JVM #Programming #LearningJourney #CoreJava #TechSkills
To view or add a comment, sign in
-
-
🚀 Most Java developers think performance = better algorithms That’s incomplete. Real performance in Java often comes from what the JVM removes, not what you write. 👉 Escape Analysis (JVM optimization) The JVM checks whether an object “escapes” a method or thread. If it doesn’t, the JVM can: ✨ Allocate it on the stack (not heap) ✨ Remove synchronization (no locks needed) ✨ Eliminate the object entirely (scalar replacement) Yes — your object might never exist at runtime. 💡 Example: public void process() { User u = new User("A", 25); int age = u.getAge(); } If u never escapes this method, JVM can optimize it to: int age = 25; ❌ No object ❌ No GC pressure ❌ No overhead 📉 Where developers go wrong: • Creating unnecessary shared state • Overusing synchronization • Forcing objects onto the heap ✅ What you should do instead: • Keep objects local • Avoid unnecessary sharing between threads • Write code the JVM can optimize 🔥 Key Insight: Performance in Java isn’t just about writing efficient code. It’s about writing code the JVM can optimize. If you ignore this, you’re solving the wrong problem. #Java #JVM #Performance #SoftwareEngineering #BackendDevelopment
To view or add a comment, sign in
-
Day 33/100 — Threads & Multithreading ⚡ Java can do multiple things at the same time using threads. Thread lifecycle: NEW → RUNNABLE → RUNNING → WAITING → TERMINATED 2 ways to create threads: // Method 1: extend Thread class MyThread extends Thread { public void run() { println("Running!"); } } new MyThread().start(); // NOT run()! // Method 2: Runnable lambda (preferred!) Thread t = new Thread(() -> println("Lambda thread!")); t.start(); Most important rule: ALWAYS call start() — NOT run()! → run() = normal method call (same thread) → start() = creates new thread and calls run() 3 things to remember: → Prefer Runnable over extending Thread → start() not run() → Multiple threads = race conditions possible! 🎯 Challenge: Create 3 threads that each print their name 5 times. Observe the interleaved output! #Java #Threads #Multithreading #CoreJava #100DaysOfJava #100DaysOfCode
To view or add a comment, sign in
-
-
Most Java performance issues don’t show up in code reviews They show up in object lifetimes. Two pieces of code can look identical: same logic same complexity same output But behave completely differently in production. Why? Because of how long objects live. Example patterns: creating objects inside tight loops → short-lived → frequent GC holding references longer than needed → objects move to old gen caching “just in case” → memory pressure builds silently Nothing looks wrong in the code. But at runtime: GC frequency increases pause times grow latency becomes unpredictable And the worst part? 👉 It doesn’t fail immediately. 👉 It degrades slowly. This is why some systems: pass load tests work fine initially then become unstable weeks later Takeaway: In Java, performance isn’t just about what you do. It’s about how long your data stays alive while doing it. #Java #JVM #Performance #Backend #SoftwareEngineering
To view or add a comment, sign in
-
Day 7 of #100DaysOfCode — Java is getting interesting ☕ Today I explored the Java Collections Framework. Before this, I was using arrays for everything. But arrays have one limitation — fixed size. 👉 What if we need to add more data later? That’s where Collections come in. 🔹 Key Learnings: ArrayList grows dynamically — no size worries Easy operations: add(), remove(), get(), size() More flexible than arrays 🔹 Iterator (Game changer) A clean way to loop through collections: hasNext() → checks next element next() → returns next element remove() → safely removes element 🔹 Concept that clicked today: Iterable → Collection → List → ArrayList This small hierarchy made everything much clearer. ⚡ Array vs ArrayList Array → fixed size ArrayList → dynamic size Array → stores primitives ArrayList → stores objects Still exploring: Set, Map, Queue next 🔥 Consistency is the only plan. Showing up every day 💪 If you’re also learning Java or working with Collections — let’s connect 🤝 #Java #Collections #ArrayList #100DaysOfCode #JavaDeveloper #LearningInPublic
To view or add a comment, sign in
-
Garbage Collection in Java – How JVM Cleans Memory 🧹 In C/C++, memory must be freed manually. In Java? The JVM handles it automatically using Garbage Collection. How it works: ▸ GC runs automatically inside the JVM ▸ Identifies objects with NO active references ▸ Removes them from Heap memory ▸ Frees space for new object allocation JVM Heap Structure: 1️⃣ Young Generation → New objects are created here → Minor GC runs frequently (fast cleanup) 2️⃣ Old Generation → Long-living objects move here → Major/Full GC runs here (slower & expensive) 3️⃣ Metaspace (Java 8+) → Stores class metadata → Replaced PermGen Can we force GC? ▸ "System.gc()" only suggests the JVM to run GC ▸ Execution is NOT guaranteed Behind the scenes: → JVM uses different GC algorithms like: ▸ Serial GC ▸ G1 GC (default in modern JVMs) ▸ ZGC / Shenandoah (low-latency collectors) Best Practices: → Avoid creating unnecessary objects → Don’t rely on "System.gc()" → Close resources using try-with-resources → Nullify references only when necessary (e.g., large unused objects) #Java #SpringBoot #GarbageCollection #JVM #JavaDeveloper #BackendDeveloper
To view or add a comment, sign in
-
-
⚠️ Why Java Killed PermGen (And What Replaced It) Before Java 8, JVM had PermGen (Permanent Generation) A special memory region inside the heap used for: Class metadata Method metadata String intern pool (pre-Java 7) Static variables The Problem was with PermGen as it had a fixed size: -XX:MaxPermSize=256m Sounds fine until: Applications dynamically load classes Frameworks create proxies (Spring, Hibernate) ClassLoaders don’t get garbage collected 👉 Boom: OutOfMemoryError: PermGen space Very common in: App servers Long-running systems Hot-deploy environments 🧠 Enter Metaspace (Java 8+) PermGen was removed and replaced with Metaspace Key change: Moved class metadata OUT of heap → into native memory ⚡ What Changed? Memory Location Native memory Size Dynamic (auto grows) Tuning Minimal OOM Errors Frequent Much rarer 🧠 Why This Was a Big Deal Metaspace: Grows dynamically (no fixed ceiling by default) Reduces OOM crashes Simplifies JVM tuning Handles dynamic class loading better But It’s Not “Unlimited" If not controlled It can still cause: OutOfMemoryError: Metaspace So you can still set limits: -XX:MaxMetaspaceSize=512m 🧠 What Actually Lives in Metaspace? Class metadata Method metadata Runtime constant pool NOT: Objects (Heap) Stack frames (Stack) PermGen failed because it was fixed. Metaspace works because it adapts. #Java #JVM #MemoryManagement #Metaspace #PerformanceEngineering #BackendDevelopment #JavaInternals #LearnInPublic
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