#Post6 In the previous post, we understood how our code runs: Code → JVM → Process → Threads (https://lnkd.in/dns348v6) Now let’s go one step deeper What actually happens inside a process when it executes? When a Java program runs, the JVM creates a process. Inside that process, memory and execution are organized into different parts. 1. Heap Memory (Shared) This is where objects created using the "new" keyword are stored. • Shared by all threads within the same process • Not shared across different processes • Threads can read and modify data Because multiple threads access it → synchronization is required 2. Code Segment (Shared) Contains the bytecode (instructions to execute). • Read-only • Shared across all threads 3. Data Segment (Shared) Stores static and global variables. • Shared across all threads • Can be modified Synchronization is required when multiple threads update data 4. Stack (Thread-specific) Each thread has its own stack. • Stores method calls • Stores local variables • Not shared between threads 5. Program Counter (Thread-specific) Each thread has its own program counter. • Points to the current instruction being executed • Moves forward as execution progresses 6. Registers (Thread-specific) Each thread uses CPU registers to store temporary/intermediate data during execution. (We will explore how registers are used during context switching in upcoming posts) Important Understanding Inside a process: • Heap + Code + Data → Shared across threads • Stack + Program Counter + Registers → Private to each thread This separation is what makes multithreading both powerful and complex. Key takeaway Threads share memory (heap), but execute independently using their own stack and execution state. In the next post, we’ll explore Registers and how CPU switches between threads (context switching). #Java #SoftwareEngineering #Multithreading #BackendDevelopment #Programming
Java Multithreading: Process Memory Organization
More Relevant Posts
-
Deep Dive into JVM Internals — Beyond the Basics 🔲 Slide 1 — The Nesting Doll JDK ⊃ JRE ⊃ JVM. Three nested layers. Not three separate tools. Most developers have used all three for years without knowing the difference. 🔗 Slide 2 — Class Loader Every class request travels UP the chain before any loader handles it. Bootstrap → Platform → Application → Custom. This parent delegation contract is why you can never shadow java.lang.String — no matter how hard you try. 🧠 Slide 3 — Memory Architecture Per-thread → PC Register · JVM Stack · Native Stack Shared → Heap (Eden → Survivor → Old Gen) · Metaspace · Code Cache · Constant Pool One fact most devs miss: Every Java object costs 12–16 bytes of header before your first field. That's why int[] uses 8× less memory than Integer[]. ⚡ Slide 4 — JIT Tiered Compilation T0 → T1 → T2 → T3 → T4 (C2 peak) C2 does inlining, escape analysis, lock elision, loop unrolling, and scalar replacement. If an object never leaves a method → C2 puts it on the stack. Zero heap allocation. Zero GC pressure. ♻️ Slide 5 — GC Internals All collectors share tri-colour marking: White → Gray → Black. Serial · Parallel · G1 (default, Java 9+) · ZGC · Shenandoah ZGC's trick: GC state lives in unused bits of 64-bit pointers. Relocation happens concurrently. Threads never pause. Sub-1ms guaranteed. 🔁 Slide 6 — Bytecode → CPU .java → javac → .class → ClassLoader → Interpreter → JIT → Code Cache → CPU The OS is involved at every step: thread scheduling · mmap for heap · SIGSEGV → NullPointerException Java 21 virtual threads intercept I/O before the syscall. Millions of threads. Near-zero OS overhead. 📋 Slide 7 — Quick Reference Card Essential JVM flags · diagnostic tools · jstack · jmap · async-profiler A cheat sheet worth bookmarking. #Java #JVM #BackendDevelopment #SystemDesign #Performance #SoftwareEngineering
To view or add a comment, sign in
-
Stack vs Heap Memory in Java – Where Does Your Data Live? 🧠 Stack Memory: ▸ Method calls + local variables ▸ LIFO (Last In, First Out) ▸ Very fast, auto-cleared after method ends ▸ Each thread has its own stack Heap Memory: ▸ Stores objects & instance variables ▸ Shared across threads ▸ Managed by Garbage Collector ▸ Slower than Stack, can throw OutOfMemoryError Example: void demo() { int x = 10; String s = new String("Java"); } ▸ x → Stack ▸ s (reference) → Stack ▸ "Java" object → Heap Rule: → Primitives → Stack → References → Stack → Objects → Heap #Java #SpringBoot #BackendDevelopment #Memory #JavaDeveloper
To view or add a comment, sign in
-
-
Stack vs Heap Memory in Java – Where Does Your Data Live? 🧠 Stack Memory: ▸ Method calls + local variables ▸ LIFO (Last In, First Out) ▸ Very fast, auto-cleared after method ends ▸ Each thread has its own stack Heap Memory: ▸ Stores objects & instance variables ▸ Shared across threads ▸ Managed by Garbage Collector ▸ Slower than Stack, can throw OutOfMemoryError Example: void demo() { int x = 10; String s = new String("Java"); } ▸ x → Stack ▸ s (reference) → Stack ▸ "Java" object → Heap Rule: → Primitives → Stack → References → Stack → Objects → Heap #Java #SpringBoot #BackendDevelopment #Memory #JavaDeveloper
To view or add a comment, sign in
-
-
If your class name looks like CoffeeWithMilkAndSugarAndCream… you’ve already lost. This is how most codebases slowly break: You start with one clean class. Then come “small changes”: add logging add validation add caching So you create: a few subclasses… then a few more or pile everything into if-else Now every change touches existing code. And every change risks breaking something. That’s not scaling. That’s slow decay. The Decorator Pattern fixes this in a simple way: Don’t modify the original class. Wrap it. Start with a base object → then layer behavior on top of it. Each decorator: adds one responsibility doesn’t break existing code can be combined at runtime No subclass explosion. No god classes. No fragile code. Real-world example? Java I/O does this everywhere: you wrap streams on top of streams. The real shift is this: Stop thinking inheritance. Start thinking composition. Because most “just one more feature” problems… are actually design problems. Have you ever seen a codebase collapse under too many subclasses or flags? #DesignPatterns #LowLevelDesign #SystemDesign #CleanCode #Java #SoftwareEngineering #OOP Attaching the decorator pattern diagram with a simple example.
To view or add a comment, sign in
-
-
𝗧𝗵𝗲 𝗝𝗮𝘃𝗮 𝘀𝘄𝗶𝘁𝗰𝗵 𝘀𝘁𝗮𝘁𝗲𝗺𝗲𝗻𝘁 𝘁𝘂𝗿𝗻𝗲𝗱 𝟯𝟬 𝘁𝗵𝗶𝘀 𝘆𝗲𝗮𝗿 Here's the short version: What started as a C-style branching construct is now a declarative data-matching engine — and the JVM internals behind it are genuinely fascinating. What I learned going deep on this: → Early switch relied on jump tables — fast, but fall-through bugs were silent and destructive → Java added definite assignment rules, preventing uninitialized variables from slipping through → The JVM picks between tableswitch (O(1)) and lookupswitch (O(log n)) based on how dense your cases are → String switching since Java 7 uses hashCode + equals internally — it's not magic, it's two passes → Java 14 made switch an expression, which killed fall-through at the language level → Modern Java (21+) adds pattern matching with type binding and null handling — code reads like a description of data → invokedynamic enables runtime linking, replacing rigid compile-time dispatch tables → Java 25 enforces unconditional exactness in type matching — no more silent data loss • The real shift isn't syntax. It's the question switch answers. Old: "Where should execution go?" New: "What is the shape of this data?" That's not just a feature upgrade. That's a change in how you think about branching. Which of these surprised you most? Drop it in the comments. A special thanks to Syed Zabi Ulla sir at PW Institute of Innovation for their clear explanations and continuous guidance throughout this topic. #Java #Programming #SoftwareEngineering #JVM #LearningInPublic #CodingJourney
To view or add a comment, sign in
-
Problem :- Plus One (LeetCode 66) Problem Statement :- You are given a large integer represented as an integer array digits, where each digits[i] is a digit of the integer. The digits are ordered from most significant to least significant. Increment the integer by one and return the resulting array of digits. Approach :- Carry Handling i - Traverse from the last digit ii - If digit < 9 → increment and return iii - If digit == 9 → make it 0 and carry forward iv - If all digits are 9 → create new array v - Time Complexity : O(n) vi - Space Complexity : O(1) class Solution { public int[] plusOne(int[] digits) { int n = digits.length; for(int i = n - 1; i >= 0; i--) { if(digits[i] < 9) { digits[i]++; return digits; } digits[i] = 0; } int[] result = new int[n + 1]; result[0] = 1; return result; } } How would you optimize this further? #Java #DSA #LeetCode #CodingJourney #LearnInPublic #SoftwareEngineering #Arrays
To view or add a comment, sign in
-
-
Java Arrays: The Ultimate Building Blocks Before building complex data structures, the foundation needs to be rock solid. Arrays are the ultimate building blocks. Today, I locked down the 4 core operations: 1. Declare: Reserving contiguous memory. 2. Initialize: Populating the data. 3. Access: The magic of O(1). 4. Traverse: Looping through the elements. The biggest takeaway? Understanding fixed memory allocation in Java is crucial before moving to dynamic structures like ArrayLists or HashMaps. #DSA #Java #ArrayBasics
To view or add a comment, sign in
-
-
🚀 Ever wondered what actually happens under the hood when you run a Java program? It’s not just magic; it’s the Java Virtual Machine (JVM) at work. Understanding JVM architecture is the first step toward moving from "writing code" to "optimizing performance." Here is a quick breakdown of the core components shown in the diagram: 1️⃣ Classloader System The entry point. It loads, links, and initializes the .class files. It ensures that all necessary dependencies are available before execution begins. 2️⃣ Runtime Data Areas (Memory Management) This is where the heavy lifting happens. The JVM divides memory into specific areas: Method/Class Area: Stores class-level data and static variables. Heap Area: The home for all objects. This is where Garbage Collection happens! Stack Area: Stores local variables and partial results for each thread. PC Registers: Keeps track of the address of the current instruction being executed. Native Method Stack: Handles instructions for native languages (like C/C++). 3️⃣ Execution Engine The brain of the operation. It reads the bytecode and executes it using: Interpreter: Reads bytecode line by line. JIT (Just-In-Time) Compiler: Compiles hot spots of code into native machine code for massive speed boosts. Garbage Collector (GC): Automatically manages memory by deleting unreferenced objects. 4️⃣ Native Interface & Libraries The bridge (JNI) that allows Java to interact with native OS libraries, making it incredibly versatile. 💡 Pro-Tip: If you are debugging OutOfMemoryError or StackOverflowError, knowing which memory area is failing is half the battle won. #Java #JVM #BackendDevelopment #SoftwareEngineering #ProgrammingTips #TechCommunity #JavaDeveloper #CodingLife
To view or add a comment, sign in
-
-
💡How the JVM really manages memory When I first started with Java, I thought memory management was handled by the JVM, but working on real backend systems changed that completely. Here’s a simplified view that helped me understand how things actually work: 🔹 Heap (where objects live) The Heap is divided into two generations: ➡️ Young Generation • Eden Space: where all new objects are created • Survivor Spaces (S0, S1): where objects go if they survive initial GC cycles ➡️ Old Generation • Stores long-lived objects that survived multiple GC cycles ✅How Garbage Collection works: 1️. Objects are created in Eden 2️. When Eden fills up → Minor GC is triggered 3️. Surviving objects move to Survivor spaces 4️. After several cycles → moved to Old Generation 5️. When Old Gen fills up → Major GC (Full GC) occurs Why this matters in real life: • Too many objects in Eden can lead to frequent Minor GC cycles, increasing CPU usage and affecting performance • When a memory leak happens the old Generation gets filled up and the JVM triggers the full GC which makes the application slow down • Bad object lifecycle management leads to serious production issues. 🔹Stack Each thread has its own stack (method calls, local variables) 🔹Metaspace Stores class metadata 📌Backend engineering is not just about code, it’s about how your code behaves in memory. #java #jvm #garbagecollection #backend #softwareengineering #springboot #performance #microservices
To view or add a comment, sign in
-
🚀 Solved: Find Dominant Index (LeetCode) Just solved an interesting problem where the goal is to find whether the largest element in the array is at least twice as large as every other number. 💡 Approach: 1. First, traverse the array to find the maximum element and its index. 2. Then, iterate again to check if the max element is at least twice every other element. 3. If the condition fails for any element → return "-1". 4. Otherwise → return the index of the max element. 🧠 Key Insight: Instead of comparing all pairs, just track the maximum and validate it — keeps the solution clean and efficient. ⚡ Time Complexity: O(n) ⚡ Space Complexity: O(1) 💻 Code (Java): class Solution { public int dominantIndex(int[] nums) { int max = -1; int index = -1; // Step 1: find max and index for (int i = 0; i < nums.length; i++) { if (nums[i] > max) { max = nums[i]; index = i; } } // Step 2: check condition for (int i = 0; i < nums.length; i++) { if (i == index) continue; if (max < 2 * nums[i]) { return -1; } } return index; } } 🔥 Got 100% runtime and 99%+ memory efficiency! #LeetCode #DSA #Java #Coding #ProblemSolving #Algorithms
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