How try-with-resources Handles Dependent Resources in Java Last week, I talked about how try-with-resources made it easier to close connections automatically. But what about when one resource depends on another — like a ResultSet that relies on a PreparedStatement, which relies on a Connection? Before (old way): Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = dataSource.getConnection(); stmt = conn.prepareStatement("SELECT * FROM orders WHERE customer_id = ?"); stmt.setInt(1, id); rs = stmt.executeQuery(); while (rs.next()) { process(rs); } } finally { if (rs != null) rs.close(); if (stmt != null) stmt.close(); if (conn != null) conn.close(); } After (try-with-resources): try (Connection conn = dataSource.getConnection(); PreparedStatement stmt = conn.prepareStatement("SELECT * FROM orders WHERE customer_id = ?"); ResultSet rs = stmt.executeQuery()) { while (rs.next()) { process(rs); } } Java automatically closes everything in reverse order of creation: ResultSet → Statement → Connection No leaks, no nested finally blocks, no forgotten close calls. It’s small things like this that make Java cleaner every release. 👉 Did you know try-with-resources handled dependencies this neatly? #Java #CleanCode #SoftwareEngineering #Refactoring #Java17 #BestPractices
How try-with-resources handles dependent resources in Java
More Relevant Posts
-
“Everyone says they know Java Strings… until this happens 👇” What’s the output? String s1 = "Java"; String s2 = "Java"; String s3 = new String("Java"); System.out.println(s1 == s2); System.out.println(s1 == s3); System.out.println(s1.equals(s3)); Most will say: “All true — same value!” But nope ❌ Output: true false true Why? Because "==" compares references (memory location) .equals() compares content (actual string value) s1 and s2 point to the same literal in the String pool, but new String("Java") creates a new object in the heap, so the reference check fails even though the content is identical. Lesson? 👉 Knowing how Java handles memory and strings is what separates a coder from a problem solver.
To view or add a comment, sign in
-
Finding common elements between two lists using Java Streams can be approached with performance in mind. Consider the following two lists: List<Integer> intList1 = List.of(1, 2, 3, 4, 5, 6); List<Integer> intList2 = List.of(2, 4, 6, 8, 10); Here are three options to find the common elements: **Option 1:** ```java System.out.println(intList1.stream() .filter(intList2::contains) .collect(Collectors.toSet())); ``` This method is straightforward but has a time complexity of O(n * m) because for each element in intList1, the `intList2::contains` checks the entire list. This is not efficient for large lists. **Option 2:** ```java Set<Integer> set2 = new HashSet<>(intList2); System.out.println(intList1.stream() .filter(set2::contains) .collect(Collectors.toSet())); ``` In this approach, the time complexity improves to O(n + m) since the average time for a HashSet lookup is O(1). **Option 3:** ```java Set<Integer> common = new HashSet<>(intList1); System.out.println(common.retainAll(intList2)); ``` This option utilizes a built-in function and also achieves a time complexity of O(n + m), while being simpler in implementation. By considering these options, you can choose the most efficient method for your specific use case.
To view or add a comment, sign in
-
💡 Did you know that Sequenced Collections were introduced in Java 21 to solve the lack of a unified API for ordered collections? Before Java 21, many collections were already "sequenced" (such as: List, LinkedHashSet, LinkedHashMap, TreeSet, TreeMap) However, they didn't share a common interface that reflected this property. This led to inconsistent APIs. For example: • To get the first element of a List, you'd use list.get(0), but there was no equivalent for an ordered Set or Map. • To get the last element of a List, you'd use list.get(list.size() - 1), while for a LinkedHashSet, you'd have to iterate through the entire set. • To reverse a list you could use Collections.reverse(list), but for a LinkedHashSet or TreeMap, you’d need to copy elements into another structure. 🔧 Sequenced Collections fix this by introducing new interfaces: 🔹 SequencedCollection<E>: The main interface, which extends Collection<E>. It represents any collection with a defined order. 🔹SequencedSet<E>: Extends SequencedCollection<E> and Set<E>. Implemented by classes like LinkedHashSet. 🔹SequencedMap<K, V>: Extends Map<K, V>. Implemented by classes like LinkedHashMap. Existing classes like List, Deque, LinkedHashSet, and LinkedHashMap have been retrofitted to implement these new interfaces. 🔑 Key Methods The interface SequencedCollection provides a standard set of methods for accessing elements at either end: • getFirst(): Gets the first element • getLast(): Gets the last element • addFirst(E): Adds an element to the beginning. • addLast(E): Adds an element to the end. • removeFirst(): Removes and returns the first element. • removeLast(): Removes and returns the last element. • reversed(): This is a key feature. It returns a reverse-ordered view of the collection. #Java #Java21 #SequencedCollections #SoftwareDevelopment #LearningJava
To view or add a comment, sign in
-
-
The image is a flowchart that describes the three main steps involved in compiling and executing a Java program. Step 1: Write source code. A programmer uses an editor to write the source code, which is saved as a .java file (e.g., Xxx.java). Step 2: Compile. The Java Compiler (javac) translates the .java source code into Java Bytecode, which is saved as a .class file (e.g., Xxx.class). This bytecode is an intermediate code that is not specific to any single machine. Step 3: Execute. The Java Runtime (java) takes the bytecode as input, along with any user input, and executes the program to produce an output. This execution is performed by the Java Virtual Machine (JVM), which interprets the bytecode into machine-specific code.
To view or add a comment, sign in
-
-
💡 Understanding Call by Value vs Call by Reference in Java 🔹 Call by Value: A copy of the actual value is passed to the method. Changes made inside the method don’t affect the original variable. Example: void modify(int x) { x = 50; } Here, changing x inside the method won’t change the original variable’s value. 🔹 Call by Reference (Conceptual): Instead of passing the value, the reference (address) of the variable is passed. Any change made affects the original object. Example: void modify(int[] arr) { arr[0] = 50; } Since the array’s reference is passed, modifying it changes the original array. 🔸 Call by Value → Works on Copies 🔸 Call by Reference → Works on Original Data #Java #Callbyvaluevscallbyrefernce #LearningJourney
To view or add a comment, sign in
-
-
In modern Java applications, generating dynamic text is a common need — whether it’s building personalized email content, log messages, SQL queries, or configuration templates. Templating and placehol https://lnkd.in/d8_XFUgg
To view or add a comment, sign in
-
🧠 ThreadLocal — The Hidden Power (and Danger) in Java Ever used ThreadLocal? It’s one of Java’s most mysterious yet powerful tools. It can make your code thread-safe... or cause a silent memory leak 😬 --- 🔹 What it actually does ThreadLocal gives each thread its own copy of a variable. That means no synchronization, no race conditions — just thread-specific data. Perfect for storing things like user sessions, DB connections, or request IDs. Example: private static final ThreadLocal<String> userName = new ThreadLocal<>(); userName.set("Tushar"); System.out.println(userName.get()); // Only visible to current thread --- 🔹 The hidden danger ⚠️ When a thread is reused (like in thread pools), its ThreadLocal value doesn’t automatically reset. If you forget to call remove(), you might end up leaking memory or passing wrong data to the next request. userName.remove(); // Always clean up after use! --- 🔹 Why you should care Spring uses ThreadLocal under the hood for things like RequestContextHolder and TransactionSynchronizationManager. If you understand it, you’ll debug faster and avoid those “it works locally but fails in prod” moments 💥 --- 💬 Your turn: Have you ever faced weird data issues in multi-threaded code? Maybe ThreadLocal was silently involved 😉 Share your story below 👇 #Java #Multithreading #ThreadLocal #BackendDevelopment #SpringBoot #JavaDeveloper #CleanCode
To view or add a comment, sign in
-
🚀Day 93/100 #100DaysOfLeetCode 🧩Problem: Remove Duplicates from Sorted List II✅ 💻Language: Java 🧠Approach: This problem requires removing all duplicate nodes from a sorted linked list, leaving only unique elements. Steps: 1️⃣Use a dummy node to handle edge cases easily (like when the first few nodes are duplicates). 2️⃣Use two pointers — one (prev) to track the previous node and another (head) to traverse the list. 3️⃣Whenever duplicate values are found (head.val == head.next.val), move head forward until all duplicates are skipped. 4️⃣Link prev.next to the next distinct node. 5️⃣Move prev forward only when no duplicates are found. This ensures that only unique nodes remain in the resulting linked list. 🔑Key Takeaways: 🔹Handling linked list edge cases effectively using a dummy node simplifies logic. 🔹Two-pointer techniques are powerful for in-place list manipulation. 🔹Proper pointer management avoids unnecessary complexity and extra memory usage. ⚡Performance: ⏱️Runtime: 0 ms (Beats 100%) 💾Memory: 43.51 MB (Beats 24.99%) #100DaysOfLeetCode #Java #LinkedList #LeetCode #CodingJourney #DSA #CodingChallenge #ProblemSolving
To view or add a comment, sign in
-
-
🧠 Why You Should Start Using Java’s record Keyword — and When Not To ⚡ If you’ve been writing DTOs or POJOs with 10+ lines of boilerplate — getters, setters, equals, hashCode, toString — it’s time to meet your new best friend: 👉 record (introduced in Java 14) --- 💡 What Is a Record? A record is a compact, immutable data carrier. It automatically provides: Constructor 🏗️ getters() equals() & hashCode() toString() All in just one line of code 👇 public record User(String name, int age) {} That’s it. No Lombok, no boilerplate, no noise. --- 🚀 Why It’s Powerful ✅ Reduces clutter — focus on logic, not boilerplate. ✅ Perfect for DTOs, API responses, or configuration models. ✅ Immutable by default (thread-safe and predictable). --- ⚠️ But Here’s the Catch Not every class should be a record ❌ Avoid using records when: You need mutable state (values change after creation). You rely on inheritance (records can’t extend classes). You want to add business logic or complex behavior. Records are meant for data representation, not for service logic. --- 🧩 Quick Tip If you’re using Spring Boot, records work beautifully with: @RequestBody (JSON mapping) @ConfigurationProperties JPA projections (read-only views) But not great as JPA entities — because they’re immutable and final. --- 💬 Let’s Talk Have you tried using records in your projects yet? 👉 Share your experience — love them or still sticking with Lombok? #Java #Java17 #CleanCode #BackendDevelopment #Records #SoftwareEngineering #CodeQuality
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