**Post 7 📘 Effective Java – Item 7** “Eliminate obsolete object references” One of the most **silent bugs in Java** is not a crash… It’s a **memory leak**. Java has Garbage Collection, but **GC is not magic**. If *you* keep references, GC can’t help you. 🔍 **Common mistake** We assume that once an object is “logically unused”, Java will clean it up. But if a reference still exists → **memory leak**. 💡 **Classic example** Implementing your own stack, cache, or listener list. If you pop an element from a stack but don’t null out the reference: ➡️ Object stays in memory ➡️ GC cannot reclaim it ✅ **Best practices** * Set references to `null` once they are no longer needed * Be extra careful with: * Custom data structures * Static fields * Caches * Listeners & callbacks * Prefer **weak references** (`WeakHashMap`) for caches when applicable 🧠 **Key takeaway** > Garbage Collection works on *reachability*, not *usefulness*. Writing clean Java isn’t just about syntax or performance — it’s also about **memory hygiene**. This one habit can save you from **production memory leaks** that are extremely hard to debug. source - Effective Java ~ Josch bloch #EffectiveJava #Java #MemoryManagement #GarbageCollection #CleanCode #SoftwareEngineering #BackendDevelopment
Eliminate Java Memory Leaks with Effective Reference Management
More Relevant Posts
-
Until now, our Java programs knew all the values in advance. But real programs become useful only when they can listen to the user. Think about real life: 📝 A form is meaningful only when someone fills it. 🏧 An ATM works only after you enter details. A Java program also needs a way to listen 👂. That’s where user input comes in. 🛠️ 𝐔𝐬𝐞𝐫 𝐈𝐧𝐩𝐮𝐭 𝐢𝐧 𝐉𝐚𝐯𝐚 (𝐔𝐬𝐢𝐧𝐠 𝐒𝐜𝐚𝐧𝐧𝐞𝐫) Java provides a built-in class called Scanner to read input from the user while the program is running. There’s a simple flow involved: -->𝘐𝘮𝘱𝘰𝘳𝘵 𝘵𝘩𝘦 𝘚𝘤𝘢𝘯𝘯𝘦𝘳 𝘤𝘭𝘢𝘴𝘴 Before using Scanner, Java must be told where it comes from.This is done using import java.util.Scanner; -->𝘊𝘳𝘦𝘢𝘵𝘦 𝘢 𝘚𝘤𝘢𝘯𝘯𝘦𝘳 𝘰𝘣𝘫𝘦𝘤𝘵 The Scanner object is created using System.in , which means input will be read from the keyboard ⌨️. -->𝘙𝘦𝘢𝘥 𝘶𝘴𝘦𝘳 𝘪𝘯𝘱𝘶𝘵 Different methods are used based on the data type: • nextLine() → text • nextInt() → whole numbers • nextDouble() → decimal values -->𝘜𝘴𝘦 𝘵𝘩𝘦 𝘪𝘯𝘱𝘶𝘵 Once the input is stored in variables, the program can display it, compare it, or apply logic ⚙️. -->𝘊𝘭𝘰𝘴𝘦 𝘵𝘩𝘦 𝘚𝘤𝘢𝘯𝘯𝘦𝘳 Closing the Scanner releases the input resource after the program finishes ✅. This small setup is what transforms a static program into an interactive one ✨. I’ve also attached a simple Java program that takes input from the user and uses it - feel free to go through it for better understanding. #Java #CoreJava #JavaBasics #LearningJourney #Programming #BuildInPublic
To view or add a comment, sign in
-
-
-> Text Blocks in Java Introduced in Java 15, text blocks make it easy to write multiline strings without messy formatting. 🔹 What is a Text Block? A text block is a multiline string written using triple quotes: " content """ It preserves formatting and removes the need for escape characters. 🧩 Problem with old multiline strings Before text blocks: String json = "{\n" + " \"name\": \"Vijay\",\n" + " \"age\": 25\n" + "}"; Hard to read. Hard to maintain. ✅ With Text Blocks String json = """ { "name": "Vijay", "age": 25 } """; ✔ Clean ✔ Readable ✔ No \n ✔ No escaping mess 🔹 Why were text blocks introduced? Before Java 15: ⚠ Escape characters everywhere ⚠ Poor readability ⚠ Difficult to maintain JSON/XML/SQL ⚠ Formatting bugs Text blocks solve this by: ✅ Preserving indentation ✅ Supporting multiline text naturally ✅ Improving readability ✅ Making embedded data easier 🔹 Real-world use cases 📦 JSON payloads 📄 XML responses 🗄 SQL queries 📜 HTML templates 📊 API test data 🧪 Unit test inputs Anywhere multiline text is needed. 🧩 Example: SQL Query String query = """ SELECT * FROM users WHERE age > 18 ORDER BY name """; Much closer to real SQL. 🎯 Interview Tip If interviewer asks: What is the advantage of text blocks? Answer: 👉 They improve readability of multiline strings and remove the need for escape characters, especially useful for JSON, SQL, and XML. 🏁 Key Takeaways ✔ Introduced in Java 15 ✔ Multiline string support ✔ Cleaner formatting ✔ No escape clutter ✔ Better readability ✔ Ideal for embedded data #Java #Java15 #TextBlocks #ModernJava #JavaFeatures #CleanCode #ProgrammingConcepts #BackendDevelopment #JavaDeepDive #TechWithVijay #VFN #vijayfullstacknews
To view or add a comment, sign in
-
-
📌 Instance Variable vs Local Variable in Java – In Java, variables are classified based on where they are declared and how long they exist in memory. Two important types are Instance Variables and Local Variables. ✅ 1️⃣ Instance Variable in Java 👉 An instance variable is a variable declared inside a class but outside all methods. It belongs to an object (instance) of the class. 👉 Key Features: 🔹Declared inside class but outside methods 🔹Each object gets separate memory 🔹Scope is entire class 🔹Lifetime is as long as the object exists 🔹Stored in Heap memory... ✅ 2️⃣ Local Variable in Java 👉 A local variable is declared inside a method, constructor, or block. It is used only within that method or block. 👉 Key Features: 🔹Declared inside a method or block 🔹Scope is limited to that method 🔹Lifetime is only while method executes 🔹Must be initialized before use 🔹Stored in Stack memory 🔹Used for temporary calculations 🔹Used to store object properties.. Learning Java variables step by step makes OOP concepts crystal clear! Instance variables store object data, while local variables help in temporary calculations. 🙏 Special thanks to Anand Kumar Buddarapu sir for continuous guidance and support. 🙏A heartfelt thank you to Uppugundla Sairam Sir and Saketh Kallepu Sir for building such an inspiring learning environment , guidance and opportunities you provide make a huge difference in shaping our technical and professional journey. #Java #Variables #InstanceVariable #LocalVariable #JavaBasics #CodingJourney
To view or add a comment, sign in
-
-
📌 Strong vs Weak References in Java In Java, how an object is referenced determines whether it can be garbage collected. 1️⃣ Strong Reference This is the default type of reference. Example: Object obj = new Object(); • Object is strongly referenced • Garbage Collector will NOT collect it • As long as the reference exists, object stays in memory Most objects in Java use strong references. 2️⃣ Weak Reference A weak reference does not prevent garbage collection. Example: WeakReference<Object> ref = new WeakReference<>(new Object()); • Object can be collected at any time • GC removes it when memory is needed • Reference may return null after GC 3️⃣ Key Difference • Strong reference → object is always retained • Weak reference → object is eligible for GC 4️⃣ When Weak References Are Useful • Caching • Memory-sensitive data • Preventing memory leaks Example: WeakHashMap removes entries when keys are no longer strongly referenced. 5️⃣ Why This Matters • Strong references can cause memory leaks • Weak references allow GC to reclaim memory safely 💡 Key Takeaways: - Strong references keep objects alive - Weak references allow automatic cleanup - Choosing the right reference helps manage memory efficiently #Java #GarbageCollection #MemoryManagement #JVM #CoreJava
To view or add a comment, sign in
-
Lambda Expressions vs Anonymous Inner Classes in Java Java didn’t introduce lambdas just to reduce lines of code. It introduced them to change the way we think about behavior. Anonymous Inner Classes (Old way) Runnable r = new Runnable() { @Override public void run() { System.out.println("Running"); } }; ✔ Works ❌ Verbose ❌ Boilerplate-heavy ❌ Focuses more on structure than intent ⸻ Lambda Expressions (Modern Java) Runnable r = () -> System.out.println("Running"); ✔ Concise ✔ Expressive ✔ Focused on what, not how ⸻ Why Lambdas are better 🔹 Less noise, more intent You read the logic, not the ceremony. 🔹 Functional programming support Lambdas work seamlessly with Streams, Optional, and functional interfaces. 🔹 Better readability Especially when passing behavior as a parameter. 🔹 Encourages stateless design Cleaner, safer, more predictable code. ⸻ When Anonymous Inner Classes still make sense ✔ When implementing multiple methods ✔ When you need local state or complex logic ✔ When working with legacy Java (<8) Remember: Lambdas are for behavior, not for stateful objects. ⸻ Bottom line If it’s a single-method interface → use Lambda If it’s complex or stateful → anonymous class is fine Modern Java isn’t about writing clever code. It’s about writing clear, readable, intention-revealing code. #Java #LambdaExpressions #AnonymousClass #CleanCode #ModernJava #SoftwareEngineering #BackendDevelopment #JavaCommunity
To view or add a comment, sign in
-
-
What is a Memory Leak in Java? Here’s the answer: Java has Garbage Collection, but memory leaks can still happen. A memory leak occurs when objects are no longer needed but are still referenced, so the Garbage Collector cannot remove them. Result: Heap memory keeps filling → eventually OutOfMemoryError Common Causes of Memory Leaks 1️⃣ Unused objects still referenced List<Object> list = new ArrayList<>(); while (true) { list.add(new Object()); // never removed } 2️⃣ Static collections Static variables live for the entire application lifecycle. static List<Object> cache = new ArrayList<>(); 3️⃣ Unclosed resources • DB connections • Streams • Sockets 4️⃣ Listeners not removed GUI or event-driven apps often leak via registered listeners. 5️⃣ Improper equals/hashCode Objects remain in HashMap/HashSet because removal fails. Why GC can’t help? GC removes only unreachable objects. If references exist → object is still “alive”. Symptoms • Increasing memory usage over time • Frequent GC runs • Slow performance • Eventually → OutOfMemoryError How to Prevent Memory Leaks ✔ Remove unused references ✔ Close resources (try-with-resources) ✔ Use WeakHashMap for caches ✔ Monitor memory with tools (VisualVM, JConsole) A memory leak in Java happens when unused objects remain referenced, preventing garbage collection and causing heap memory exhaustion over time. Follow Supriya Singh for more such interesting and helpful posts. #java #javainterviewprep #javainterviewquestions #javadeveloper
To view or add a comment, sign in
-
-
📘 Day 7 | Core Java – Concept Check🌱 Revising Core Java concepts and validating my understanding with answers 👇 1️⃣ Why does Java not support multiple inheritance with classes? -->To avoid ambiguity and complexity (diamond problem). Java achieves multiple inheritance using interfaces instead. 2️⃣ What happens if we override equals() but not hashCode()? -->It breaks the contract between equals() and hashCode(), causing incorrect behavior in hash-based collections like HashMap. 3️⃣ Can an abstract class have a constructor? Why? --> Yes, an abstract class can have a constructor to initialize common data when a subclass object is created. 4️⃣ Why is method overloading decided at compile time? --> Because it is resolved based on method signature (method name + parameters) at compile time, not at runtime. 5️⃣ What is the difference between method overriding and method hiding? --> Overriding happens with non-static methods at runtime, while hiding happens with static methods at compile time. 6️⃣ Why can’t we create an object of an abstract class? -->Because abstract classes may contain abstract methods without implementation, and objects must have complete behavior. 7️⃣ How does polymorphism help in reducing code dependency? --> It allows programming to interfaces or parent classes, making code flexible and easy to extend without modification. 8️⃣ What is the use of the instanceof operator in Java? --> It checks whether an object belongs to a specific class or interface at runtime. Learning concepts deeply by questioning and validating answers 📚💻 #CoreJava #JavaLearning #ProgrammingConcepts #LearningJourney #MCAGraduate
To view or add a comment, sign in
-
📌 Understanding the this Keyword in Java (with a simple example) In Java, the this keyword is a reference to the current object of a class. It’s commonly used to differentiate instance variables from method or constructor parameters when they share the same name. Let’s look at a simple example 👇 class Employee { String name; int age; // Constructor Employee(String name, int age) { this.name = name; this.age = age; } void display() { System.out.println("Name: " + this.name); System.out.println("Age: " + this.age); } public static void main(String[] args) { Employee emp = new Employee("Vishnu", 28); emp.display(); } } 🔍 What’s happening here? this.name refers to the instance variable of the current object. name (without this) refers to the constructor parameter. Without this, Java would get confused between the two variables. Using this makes the code clear, readable, and bug-free. ✅ Why this is important? Avoids variable shadowing Improves code clarity Helps in constructor chaining and method calls Essential for writing clean object-oriented code Mastering small concepts like this builds a strong Java foundation 💪 #Java #OOP #Programming #Backend #Learning #CleanCode
To view or add a comment, sign in
-
🔹FUNDAMENTALS OF JAVA ✅ Why main() Must Be Public? class Hello { public static void main(String[] args) { System.out.println("Hello Java!"); } } public is an access modifier. Access modifiers control who can access a method or class. Java has: 👉public 👉private 👉protected 👉default (no modifier) When you run: java Hello You are not calling main() yourself. 👉 JVM calls main() automatically. Now think carefully: JVM is outside your class. JVM must access your main() method. If it cannot access it → program will not start. So main() must be: public So that JVM can access it from anywhere. 🔥 What Happens If You Remove public? Example: class Hello { static void main(String[] args) { System.out.println("Hello"); } } Now compile: javac Hello.java Compilation works ✔ But when you run: java Hello You get error: Main method not found in class Hello Because JVM requires: public static void main(String[] args) Exactly that signature. 🔍 Technical Reason The JVM looks specifically for: public static void main(String[] args) If it is: private ❌ protected ❌ default ❌ JVM cannot access it. Only public allows access from outside the class protected
To view or add a comment, sign in
-
-
🚀 Java Collection Framework – Explained Simply ☕ The Collection Framework in Java is used to store, manage, and process groups of objects efficiently. 1️⃣ 📃 List 🔹 Ordered collection 🔹 Allows duplicate elements 🔹 Access elements using index ✅ Common classes: ArrayList, LinkedList List<String> list = new ArrayList<>(); list.add("Java"); list.add("Spring"); list.add("Java"); 📌 Output → [Java, Spring, Java] 2️⃣ 🧮 Set 🔹 Stores unique elements only 🔹 No duplicates allowed 🔹 Faster search operations ✅ Common classes: HashSet, LinkedHashSet, TreeSet Set<Integer> set = new HashSet<>(); set.add(10); set.add(10); 📌 Output → [10] 3️⃣ 🚦 Queue 🔹 Follows FIFO (First In First Out) 🔹 Used in task scheduling & messaging systems ✅ Common classes: PriorityQueue, LinkedList Queue<String> queue = new LinkedList<>(); queue.add("Task1"); queue.add("Task2"); queue.poll(); 📌 Output → Task1 4️⃣ 🗂️ Map 🔹 Stores data as Key 🔑 – Value pairs 🔹 Keys are unique, values can repeat 🔹 Not part of Collection interface ✅ Common classes: HashMap, LinkedHashMap, TreeMap Map<Integer, String> map = new HashMap<>(); map.put(1, "Java"); map.put(2, "Spring"); 📌 Output → Java 🎯 Quick Summary ✔ List → Ordered + Duplicates allowed ✔ Set → Unique elements ✔ Queue → FIFO processing ✔ Map → Key–Value storage 💡 Strong understanding of Collections = Strong Java Developer ☕🔥 👍 Like | 💬 Comment | 🔁 Share #Java #CollectionFramework #JavaDeveloper #BackendDevelopment #Programming #CodingLife 🚀
To view or add a comment, sign in
-
Explore related topics
- Building Clean Code Habits for Developers
- Writing Clean, Dynamic Code in Software Development
- Best Practices for Writing Clean Code
- Coding Best Practices to Reduce Developer Mistakes
- Advanced Debugging Techniques for Senior Developers
- How to Write Clean, Error-Free Code
- Simple Ways To Improve Code Quality
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