🚀 Java Memory Mastery: The String Constant Pool Ever wondered how Java handles millions of strings without crashing your memory? Meet the String Constant Pool (SCP)—the JVM's secret "unique-only" library. In this breakdown, I deconstruct the "Two-Object Trap": Literals ("Hello"): Check the pool. If it’s there, reuse it. Efficient and fast. The new Keyword: Forces a brand new object into the Heap, even if the text already exists. The Pro-Tip: Use .intern() to manually move Heap strings into the pool and keep your memory footprint lean. Stop duplicating data. Start optimizing your architecture. 🛠️ #Java #BackendEngineering #SystemDesign #JVM #SoftwareDevelopment #TheBytecodePhantom
Java String Constant Pool Optimization
More Relevant Posts
-
"Architecting Knowledge" - Java Wisdom Series Post #17: Virtual Threads - Rethinking Concurrency 👇 Million threads. One JVM. Welcome to Project Loom. Why This Matters: Platform threads map 1:1 to OS threads - each consumes ~1MB stack memory. You can create maybe 4000-10000 before your JVM dies. Virtual threads are JVM-managed and stack memory is allocated dynamically on heap - you can create millions. When a virtual thread blocks on I/O, the JVM unmounts it from its carrier thread (platform thread), letting that carrier run other virtual threads. This makes blocking I/O efficient again - no more callback hell. BUT beware thread pinning: synchronized blocks prevent unmounting in Java 21-23 (fixed in 24). Use ReentrantLock for long blocking operations. Key Takeaway: Virtual threads aren't faster - they're cheaper and more scalable. Perfect for I/O-bound workloads (web servers, microservices, API calls). Don't pool them, don't cache in ThreadLocal aggressively. Write simple blocking code, let Loom handle concurrency. #Java #JavaWisdom #VirtualThreads #ProjectLoom #Concurrency #Java21 Are you still using thread pools for I/O-bound tasks? Time to go virtual! All code examples on GitHub - bookmark for quick reference: https://lnkd.in/dJUx3Rd3
To view or add a comment, sign in
-
-
Day 83 - Path Sum Checked whether a binary tree has a root-to-leaf path equal to a given target sum. Approach: • Subtract current node value from targetSum • Recursively check left and right subtrees • At leaf node, verify if remaining sum equals node value Time Complexity: O(n) Space Complexity: O(h) #Day83 #LeetCode #BinaryTree #Recursion #DSA #Java #CodingJourney
To view or add a comment, sign in
-
-
Stack vs Heap - what really goes where in Java Most explanations stop at: “Stack stores variables, Heap stores objects.” That’s not enough to actually understand it. Here’s what really matters: > Stack Memory Stores method calls and local variables Works in a LIFO (Last In, First Out) manner Very fast access Automatically cleared when method execution ends Think of it as: 👉 Temporary execution space > Heap Memory Stores objects and instance variables Shared across threads Managed by Garbage Collector Slower than stack but more flexible Think of it as: 👉 Long-term storage for objects When you create an object: - The reference is stored in the stack - The actual object is stored in the heap The difference isn’t just storage. It’s about how your program executes in memory. #Java #JVM #CSFundamentals #BackendDevelopment #SDEPrep
To view or add a comment, sign in
-
-
Stopping Threads Safely: Java does not allow killing a thread directly. Use interrupts as the “polite” way to request a thread to stop. Threads should check Thread.interrupted() or catch InterruptedException. Raw Threads vs Thread Pools With raw threads, you can interrupt them directly. With ThreadPool threads, you use ExecutorService.shutdown() or Future.cancel() to signal cancellation. Callable and Future: Wrapping tasks in Callable allows you to manage them with Future. Future.cancel(true) interrupts the task if it’s running. Useful for applying timeouts on long-running tasks. Volatile / AtomicBoolean Flags: Another approach is using a shared flag (volatile boolean stop = false;). The thread periodically checks this flag to decide whether to exit. AtomicBoolean provides thread-safe updates. Timeout Strategies: Use Thread.sleep() or scheduled tasks to enforce conditional timeouts. For blocking operations (DB calls, HTTP requests), combine interrupts with timeout-aware APIs. Example: future.get(timeout, TimeUnit.SECONDS). Practical Applications: Database Calls: Long stored procedures can be interrupted if they exceed SLA. HTTP Requests: Wrap in Future with timeout to avoid hanging threads. Schedulers: Cancel tasks after a fixed duration to maintain responsiveness. #Java #BackendDevelopment #SoftwareEngineering #MultiThreading #Concurrency #JavaPerformance #CodingTips #Programming #SystemDesign
To view or add a comment, sign in
-
🚀 Solved “Detect Cycles in 2D Grid” (LeetCode 1559) Worked on a classic graph problem and implemented an efficient DFS-based solution in Java. 🔍 Key idea: Treat the grid as an undirected graph and detect cycles by: Traversing only same-character neighbors Tracking the parent cell to avoid false cycles Identifying a cycle when visiting an already visited node (not parent) ⚡ Insight: Using a recursion stack (like in directed graphs) gives wrong results here — parent tracking is the correct approach. ⏱ Complexity: Time: O(m × n) Space: O(m × n) 📌 Also added a clean, documented version to my GitHub with test cases. 🔗 LeetCode: https://lnkd.in/d6CKa-BN 🔗 GitHub: https://lnkd.in/gnEfmGAg #Java #DSA #GraphAlgorithms #LeetCode #CodingJourney
To view or add a comment, sign in
-
-
Dynamic binding in Java feels like magic—until you realize it’s the JVM calling the shots at runtime. This post breaks down what’s happening behind the curtain when method calls don’t match reference types. What you’ll learn: 1. How .toString() behaves across reference types 2. Why runtime picks the method, not the compiler 3. Key differences between Java and C++ binding 4. How dynamic binding powers polymorphism #JavaTips #OOP #DynamicBinding #JavaInternals #RheinwerkComputingBlog #DevSkills Master the runtime rules: https://hubs.la/Q04byChg0
To view or add a comment, sign in
-
-
Dynamic binding in Java feels like magic—until you realize it’s the JVM calling the shots at runtime. This post breaks down what’s happening behind the curtain when method calls don’t match reference types. What you’ll learn: 1. How .toString() behaves across reference types 2. Why runtime picks the method, not the compiler 3. Key differences between Java and C++ binding 4. How dynamic binding powers polymorphism #JavaTips #OOP #DynamicBinding #JavaInternals #RheinwerkComputingBlog #DevSkills Master the runtime rules: https://hubs.la/Q049N3m30
To view or add a comment, sign in
-
-
Day 66 — LeetCode Progress (Java) Problem: Find the Difference of Two Arrays Required: Given two integer arrays, return: Elements present in nums1 but not in nums2 Elements present in nums2 but not in nums1 Idea: Use sets to remove duplicates and quickly check membership. Approach: Convert both arrays into sets Iterate over nums1 set: Add elements not present in nums2 set to result1 Iterate over nums2 set: Add elements not present in nums1 set to result2 Return both lists Time Complexity: O(n + m) Space Complexity: O(n + m) #LeetCode #DSA #Java #HashSet #Arrays #ProblemSolving #CodingJourney
To view or add a comment, sign in
-
-
Day 65 — LeetCode Progress (Java) Problem: Find All Numbers Disappeared in an Array Required: Given an array of size n containing numbers in the range [1, n], return all the numbers that are missing from the array. Idea: Compare the expected range [1…n] with the actual elements to identify missing values. Approach: Initialize a set containing all numbers from 1 to n. Traverse the array: Remove each element from the set The remaining elements in the set are the missing numbers. Time Complexity: O(n) Space Complexity: O(n) #LeetCode #DSA #Java #HashSet #Arrays #Algorithms #CodingJourney #100DaysOfCode
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