Memory Leaks in Java (Yes, They Exist) Many developers say this with confidence. “Java has Garbage Collection, so memory leaks don’t happen.” That sounds logical. It’s also wrong. What a memory leak really means in Java A memory leak is not about unused objects. It’s about objects that are no longer needed but still referenced. GC wants to clean them. But it can’t. Because you are still holding the reference. Common real-life causes Static collections that keep growing Caches without eviction Listeners not removed Maps storing objects forever ThreadLocals not cleared Nothing crashes immediately. Memory just keeps growing. That’s why leaks are dangerous. The simplest way to think 👉 GC removes objects 👉 GC does NOT remove references If references live forever, so do objects. A very common example static List<User> users = new ArrayList<>(); This list lives for the entire JVM lifetime. Anything added here stays forever unless removed. GC cannot help you. Why leaks show up late App works fine for days Memory slowly increases GC runs more often Performance drops Finally… OutOfMemoryError The bug was written long ago. The failure comes much later. Simple prevention mindset Be careful with static Always think about object lifetime Clear collections Design caches with limits Memory management in Java is automatic, but lifecycle management is your responsibility. Closing thought Garbage Collection is powerful. But it is not magic. Understanding references is what separates a working app from a stable one. Question Have you ever faced a slow memory growth issue that turned out to be a memory leak in Java? #Java #SpringBoot #Programming #SoftwareDevelopment #Cloud #AI #Coding #Learning #Tech #Technology #WebDevelopment #Microservices #API #Database #SpringFramework #Hibernate #MySQL #BackendDevelopment #CareerGrowth #ProfessionalDevelopment #RDBMS #PostgreSQL
Java Memory Leaks: Understanding References and Lifecycles
More Relevant Posts
-
Using java streams is about creating pipelines of operations. Data will usually travel through this pipeline and will be transformed, filtered, then will participate in the production of a final result. A pipeline is made of a series of method calls on a stream. Each call produces another stream. Then at some point, a last call produces a result. An operation that returns another stream is called an intermediate operation. On the other hand, an operation that returns something else, including void, is called a terminal operation Stream can be created from collections, arrays, custom object, iterators. A stream pipeline usually follow this path: 1. Create a stream 2. Specify intermediate operations 3. Apply terminal operator to produce final result. https://lnkd.in/dHTd2SwW
To view or add a comment, sign in
-
Understanding the importance of choosing the right data structure is a key step toward writing efficient and reliable Java applications. Two often overlooked—but extremely useful—Map implementations are LinkedHashMap and IdentityHashMap. LinkedHashMap is ideal when iteration order matters. Unlike HashMap, it maintains a predictable order of elements, typically the order in which entries were inserted. It achieves this by combining a hash table with a doubly-linked list. This makes it particularly valuable for caching, logging, or any scenario where consistent traversal order improves readability or correctness. It can also be configured to maintain access order, which is useful for implementing LRU (Least Recently Used) caches. IdentityHashMap, on the other hand, serves a very different purpose. Instead of comparing keys using equals(), it uses reference equality (==). This means two distinct objects that are “equal” in value are still treated as different keys. This behavior is intentional and useful in specialized scenarios such as object graph processing, serialization frameworks, or tracking object identity during transformations. However, it is not a drop-in replacement for HashMap and should only be used when identity semantics are explicitly required. Why this matters: Selecting the correct Map implementation is not just a performance decision—it is a correctness decision. Understanding these specialized structures allows developers to write clearer, safer, and more intentional code. Knowing your tools is part of mastering your craft. Which lesser-known Java collection do you find most useful in your projects? #java #datastructure #map #LinkedHashMap #IdentityHashMap
To view or add a comment, sign in
-
🚀 Experimenting with Multithreading in Java – Real Performance Impact Recently, I built a multi-threaded web crawler in Java to understand the real-world impact of concurrency. The crawler scrapes product data (title + price) from a paginated website and stores it in a CSV file. 🧪 The Experiment: I ran the same crawler with different thread pool sizes. Case 1: Single Thread Execution time: ~678 seconds Tasks executed sequentially. Each HTTP request completed before the next one started. Case 2: 20 Threads (FixedThreadPool(20)) Execution time dropped dramatically. Multiple product pages were fetched in parallel, significantly reducing total runtime. 💡 Key Insight: The crawler is I/O-bound, not CPU-bound. Most of the time is spent waiting on network calls and server responses. While one thread waits for a response, other threads can continue working. That’s where multithreading creates massive performance gains. 📌 What I Learned: Thread pools drastically improve throughput for I/O-heavy systems. Too many threads can hurt performance due to context switching, memory overhead, and potential server throttling. Optimal thread count depends on CPU cores and the ratio of wait time to compute time. There’s even a formula: Optimal Threads ≈ CPU Cores × (1 + Wait Time / Compute Time) 🏗 Technical Takeaways Used ExecutorService with FixedThreadPool Implemented synchronized CSV storage for thread safety Used awaitTermination() to measure actual execution time Learned the importance of safe resource sharing in concurrent systems This experiment reinforced one key lesson: Multithreading isn’t just about parallelism — it’s about understanding where your system actually waits. #Java #Multithreading #BackendDevelopment #PerformanceEngineering #Concurrency
To view or add a comment, sign in
-
One of the most underrated improvements in modern Java isn’t a framework. It’s not a new JVM feature. It’s Records. For a long time, simple data structures was treated like full-blown objects. We wrapped them in constructors, getters, equals, hashCode, toString, even when they had no real behavior. The result? More ceremony than meaning. Java Records shift the focus back to intent. When you use a record, you're saying: “This type represents data. Its identity is its values.” That small shift has big architectural consequences: • Clearer domain modeling • Stronger immutability guarantees • Fewer accidental bugs • Better API design • More predictable concurrency But records are not universal replacements for classes. They shine in the right places, and cause friction in the wrong ones. I wrote a deep dive on: – Where records improve your design – Where they break down (yes, JPA…) – How to think about them beyond syntax If you're building REST APIs, DTOs, or value objects in modern Java, this is worth a read. #Java #SoftwareArchitecture #CleanCode #BackendEngineering #SpringBoot #Programming #TechDesign
To view or add a comment, sign in
-
🧾 Java Records - When To Use & When To Avoid If you're using Java 17+ and still writing 50 lines for a simple DTO… you're missing out on Records. Introduced in Java 16, record is a special type for immutable data carriers. ✅ When To Use Records 1️⃣ For DTOs / API Request-Response Objects If your class only holds data → use record. public record UserDto(Long id, String name, String email) {} No getters. No constructor. No equals/hashCode/toString. All auto-generated. Perfect for: 1. REST APIs (Spring Boot controllers) 2. Kafka messages 3. Event payloads 4. Projection objects 2️⃣ When You Need Immutability Records are: 1. final 2. Fields are private final 3. Thread-safe by design (if fields are safe) 4. Great for clean architecture & functional-style programming. 3️⃣ Value-Based Objects If equality depends only on data → record is ideal. new UserDto(1L, "Jack", "jack@example.com") .equals(new UserDto(1L, "Jack", "jack@example.com")) // true ❌ When NOT To Use Records 1️⃣ Mutable Objects If your object needs setters → record is wrong choice. 2️⃣ JPA Entities Avoid using records as Hibernate entities. Why? 1. JPA needs no-arg constructor 2. Proxies don’t work well with final classes 3. Fields can’t be reassigned 4. Use normal class for @Entity. 3️⃣ Complex Business Logic If the class contains: 1. Heavy logic 2. Internal state changes 3. Inheritance requirements Stick to traditional class. ⚡ Quick Rule: 👉 If your class is just data → use record 👉 If your class has behavior & lifecycle → use class 👉 If you are preparing for Spring Boot backend interviews, connect & follow - I share short, practical backend concepts regularly. #SpringBoot #Backend #Java #JavaDeveloper #JavaBackend #BackendDevelopment #JavaProgramming #CleanCode #InterviewPrep #SoftwareEngineering #JavaTips
To view or add a comment, sign in
-
-
🔍 🗺️ Java Map A Map stores data as key → value pairs. 🔑 Keys must be unique 📦 Values can repeat Example: 101 → User 102 → User 103 → User If the same key is inserted again → ❌ no duplication It simply replaces the old value 🧠 Creating a Map (Design Principle) We usually write: Map<Integer, User> map = new HashMap<>(); Not: HashMap<Integer, User> map = new HashMap<>(); Because the code now depends on behavior (Map) instead of implementation (HashMap). Tomorrow I can switch to LinkedHashMap or TreeMap without rewriting the project. 🗂 Types of Map and Ordering ⚡ HashMap No order guarantee Fastest Allows one null key Allows multiple null values 📋 LinkedHashMap Maintains insertion order Slightly slower Allows one null key Allows multiple null values 🌳 TreeMap Sorted by key (ascending) Uses comparison (Comparable / Comparator) Does NOT allow null key Allows multiple null values 📌 Important Map Methods put(k, v) → insert or replace get(k) → fetch value containsKey(k) → check existence remove(k) → delete entry 🔁 Iterating a Map entrySet() = Full record (key + value) keySet() = Only keys values() = Only values ⚠️ The get() Trap map.get(key) returning null does NOT mean key absent Two possibilities: • key not present • key present but value stored is null ✔ Correct way: map.containsKey(key) 🌳 TreeMap Special Rule When using custom objects as keys: You MUST implement Comparable or provide a Comparator Otherwise → ❌ ClassCastException Because TreeMap must compare keys to sort them. GitHub Link: https://lnkd.in/gtnuNm4e 🔖Frontlines EduTech (FLM) #Java #Collections #BackendDevelopment #Programming #LearningJourney #Maps #CleanCode #ResourceManagement #AustraliaJobs #SwitzerlandJobs #NewZealandJobs #USJobs
To view or add a comment, sign in
-
-
🚀 **Java Records – Writing Less Code, Doing More** One of the most useful features introduced in Java is **Records**. They help developers create immutable data classes with minimal boilerplate. 🔹 **What is a Java Record?** A *record* is a special type of class designed to hold immutable data. Java automatically generates common methods like: * `constructor` * `getters` * `toString()` * `equals()` * `hashCode()` 📌 **Example:** ```java public record User(String name, int age) {} ``` That's it! Java automatically creates: * `name()` and `age()` accessor methods * `equals()` and `hashCode()` * `toString()` * constructor 🔹 **Why use Records?** ✅ Less boilerplate code ✅ Immutable by default ✅ Cleaner and more readable models ✅ Perfect for DTOs and data carriers 🔹 **Behind the scenes** The above record behaves roughly like writing a full class with fields, constructor, getters, equals, hashCode, and toString — but with just one line. 💡 Records are a great example of how **Java continues to evolve to make developers more productive.** Are you using Records in your projects yet? #Java #JavaDeveloper #Programming #SoftwareDevelopment #Coding #Tech
To view or add a comment, sign in
-
Java Heap Dumps might contain sensitive information; with hprof-redact, you can easily remove it. Learn more in this blog post: https://lnkd.in/dn5CUtst
To view or add a comment, sign in
-
𝗗𝗔𝗬 𝟮 – 𝗝𝗗𝗞, 𝗝𝗥𝗘, 𝗝𝗩𝗠 𝗧𝗵𝗲 𝗧𝗵𝗿𝗲𝗲 𝗣𝗶𝗲𝗰𝗲𝘀 𝗕𝗲𝗵𝗶𝗻𝗱 𝗥𝘂𝗻𝗻𝗶𝗻𝗴 𝗔 𝗝𝗮𝘃𝗮 𝗣𝗿𝗼𝗴𝗿𝗮𝗺 Yesterday we talked about something interesting: 𝗝𝗮𝘃𝗮 𝗶𝘀 𝗣𝗹𝗮𝘁𝗳𝗼𝗿𝗺 𝗜𝗻𝗱𝗲𝗽𝗲𝗻𝗱𝗲𝗻𝘁. But that raises an obvious question… If machines only understand binary and every operating system is different, 𝗛𝗼𝘄 𝗱𝗼𝗲𝘀 𝗝𝗮𝘃𝗮 𝗮𝗰𝘁𝘂𝗮𝗹𝗹𝘆 𝗿𝘂𝗻 𝗼𝗻 𝗮𝗻𝘆 𝗺𝗮𝗰𝗵𝗶𝗻𝗲? The answer lies in three important components: 𝗝𝗗𝗞 𝗝𝗥𝗘 𝗝𝗩𝗠 Let’s understand them through a simple flow. First, we write a program: ``` 𝚂𝚊𝚖𝚙𝚕𝚎.𝚓𝚊𝚟𝚊 ``` This file contains human-readable code. But machines cannot understand it. 𝗦𝗼 𝗝𝗮𝘃𝗮 𝘂𝘀𝗲𝘀 𝗮 𝗰𝗼𝗺𝗽𝗶𝗹𝗲𝗿 𝗰𝗮𝗹𝗹𝗲𝗱 𝗷𝗮𝘃𝗮𝗰. 𝗪𝗵𝗲𝗻 𝘄𝗲 𝗿𝘂𝗻: ``` 𝚓𝚊𝚟𝚊𝚌 𝚂𝚊𝚖𝚙𝚕𝚎.𝚓𝚊𝚟𝚊 ``` 𝗧𝗵𝗲 𝗰𝗼𝗺𝗽𝗶𝗹𝗲𝗿 𝗰𝗼𝗻𝘃𝗲𝗿𝘁𝘀 𝗶𝘁 𝗶𝗻𝘁𝗼: ``` 𝚂𝚊𝚖𝚙𝚕𝚎.𝚌𝚕𝚊𝚜𝚜 ``` 𝗧𝗵𝗶𝘀 𝗳𝗶𝗹𝗲 𝗰𝗼𝗻𝘁𝗮𝗶𝗻𝘀 𝗕𝘆𝘁𝗲𝗰𝗼𝗱𝗲. Bytecode is not human language. It’s not raw machine code either. It’s an intermediate language designed for the JVM. Now let's understand the three components. 1. 𝗝𝗗𝗞 (𝗝𝗮𝘃𝗮 𝗗𝗲𝘃𝗲𝗹𝗼𝗽𝗺𝗲𝗻𝘁 𝗞𝗶𝘁) JDK is the complete toolkit for Java developers. It includes: • javac (compiler) • debugger tools • development utilities • JRE In simple words: 𝗝𝗗𝗞 𝗶𝘀 𝘂𝘀𝗲𝗱 𝘁𝗼 𝗯𝘂𝗶𝗹𝗱 𝗝𝗮𝘃𝗮 𝗽𝗿𝗼𝗴𝗿𝗮𝗺𝘀. 2. 𝗝𝗥𝗘 (𝗝𝗮𝘃𝗮 𝗥𝘂𝗻𝘁𝗶𝗺𝗲 𝗘𝗻𝘃𝗶𝗿𝗼𝗻𝗺𝗲𝗻𝘁) JRE provides the environment required to run Java programs. It mainly contains: • JVM • Core Java libraries Without JRE, Java programs cannot run on a machine. 3. 𝗝𝗩𝗠 (𝗝𝗮𝘃𝗮 𝗩𝗶𝗿𝘁𝘂𝗮𝗹 𝗠𝗮𝗰𝗵𝗶𝗻𝗲) JVM reads the Bytecode (.class file) and converts it into machine-level instructions for the specific operating system. And this is where the magic happens. Windows has its own JVM. Linux has its own JVM. Mac has its own JVM. But the bytecode stays the same. That’s why Java follows the famous principle: 𝗪𝗿𝗶𝘁𝗲 𝗢𝗻𝗰𝗲, 𝗥𝘂𝗻 𝗔𝗻𝘆𝘄𝗵𝗲𝗿. 𝗢𝗻𝗲 𝗲𝗮𝘀𝘆 𝘄𝗮𝘆 𝘁𝗼 𝗿𝗲𝗺𝗲𝗺𝗯𝗲𝗿: JDK → For Developing JRE → For Running JVM → For Executing 𝗧𝗼𝗺𝗼𝗿𝗿𝗼𝘄 (𝗗𝗮𝘆 𝟯): 𝗪𝗲’𝗹𝗹 𝗳𝗶𝗻𝗮𝗹𝗹𝘆 𝗺𝗼𝘃𝗲 𝗳𝗿𝗼𝗺 𝘁𝗵𝗲𝗼𝗿𝘆 𝘁𝗼 𝗰𝗼𝗱𝗲. 𝗪𝗲’𝗹𝗹 𝗰𝗼𝘃𝗲𝗿: • The structure of a Java program • Writing our first Java program • Understanding Java Tokens (Keywords, Identifiers, Literals, Separators) • Rules and conventions for naming identifiers Because before writing real Java programs, understanding these fundamentals is critical. See you in Day 3. #Java #BackendDevelopment #Programming #LearnInPublic #Day2
To view or add a comment, sign in
-
-
Great blog post from Mark Paluch about the next big Spring Data feature that will allow better safety, DevXP and refactoring by using type-safe property references instead of Strings. https://lnkd.in/eEenb7AJ #spring #java
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