🚨 Java devs using Virtual Threads — watch out for thread-local security context leaks! If you're using MsSecurityContext() or any thread-local based security holder in a Virtual Thread setup, here's a subtle bug that can sneak into your demo or production code: 🧵 Virtual Threads reuse carrier threads. ThreadLocals don’t play nice unless explicitly cleared. Let’s say you have this: public class MsSecurityContext { private static final ThreadLocal<String> currentUser = new ThreadLocal<>(); public static void setUser(String user) { currentUser.set(user); } public static String getUser() { return currentUser.get(); } public static void clear() { currentUser.remove(); } } Now imagine this: ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor(); Runnable taskA = () -> { MsSecurityContext.setUser("Alice"); System.out.println("User in Task A: " + MsSecurityContext.getUser()); // forgot to clear! }; Runnable taskB = () -> { System.out.println("User in Task B: " + MsSecurityContext.getUser()); }; executor.submit(taskA); executor.submit(taskB); 💥 Output: User in Task A: Alice User in Task B: Alice 😱 Even though Task B never set a user, it inherited Alice’s context — because the carrier thread was reused and ThreadLocal wasn’t cleared. ✅ Fix it: Always call MsSecurityContext.clear() at the end of your task. Or better: use scoped values (Project Loom) or context propagation frameworks that are Virtual Thread-aware. I'm building dry-run demos to showcase this behavior and how to bulletproof your setup. If you're integrating Virtual Threads with Spring Security, Vert.x, or custom auth flows — let’s connect! #Java #VirtualThreads #SecurityContext #ThreadLocal #SpringBoot #Vertx #DebuggingStamina #InterviewReady #TechLeadership #DineshDebugs
Java devs: Virtual Threads and thread-local security context leaks
More Relevant Posts
-
Understanding jmap — One of Java’s Most Powerful Diagnostic Tools When your Java application starts consuming too much memory or behaving unpredictably, the real question is: What’s inside the heap? That’s where the jmap (Java Memory Map) tool comes in. jmap is a command-line utility bundled with the JDK that lets you inspect and analyze memory usage of a running JVM. It’s invaluable when debugging memory leaks, high heap consumption, or GC-related performance issues. Basic Syntax: jmap [options] <pid> (where <pid> is the process ID of your Java application) Common Usages: 1. Check the heap summary jmap -heap <pid> Shows heap configuration, memory pools, garbage collectors, and usage statistics. Useful to verify how the heap is divided between Eden, Survivor, and Old Generation spaces. 2. List loaded classes jmap -clstats <pid> Displays class loader statistics — helps identify classloader leaks or unexpected redeployments in application servers. 3. Dump the heap to a file jmap -dump:format=b,file=heapdump.hprof <pid> Creates a heap dump file that you can analyze using tools like Eclipse MAT (Memory Analyzer Tool) or VisualVM. Perfect for investigating memory leaks and object retention. 4. Print histogram of objects jmap -histo <pid> | head -20 Shows a ranked list of objects in memory — classes with the most instances and total size. Great for spotting suspicious growth patterns (e.g., millions of HashMap$Node objects). Example Scenario: Imagine your microservice keeps slowing down after hours of uptime. You run: jmap -histo <pid> | head and notice thousands of byte[] and HttpSession objects still in memory. That’s your clue — likely a memory leak in session management. Pro Tip: You can also combine jmap with jhat, jvisualvm, or mat to visually navigate heap dumps and find leaks faster. In short: jmap is your JVM’s X-ray — it shows you what’s really happening inside memory. Next time you face an OutOfMemoryError, don’t panic — grab the process ID, run jmap, and start uncovering the truth. #Java #JVM #Performance #MemoryLeak #DevTools #Troubleshooting #JavaDevelopers
To view or add a comment, sign in
-
𝙃𝙤𝙬 𝙃𝙖𝙨𝙝𝙎𝙚𝙩 𝙒𝙤𝙧𝙠𝙨 𝙄𝙣𝙩𝙚𝙧𝙣𝙖𝙡𝙡𝙮 𝙞𝙣 𝙅𝙖𝙫𝙖? Most of us use HashSet to store unique values. But inside, it works very closely with HashMap. Here’s the simple version 👇 1️⃣ HashSet internally uses a HashMap HashSet is basically a wrapper around HashMap. Everything you add in a HashSet becomes a key inside an internal HashMap. private transient HashMap<E,Object> map; private static final Object PRESENT = new Object(); The value stored in the HashMap is just a dummy object called PRESENT. --- 2️⃣ When you call add(value) HashSet actually does: map.put(value, PRESENT); So the full HashMap internal logic applies: hashing → bucket selection → equals() → collision handling, etc. --- 3️⃣ How duplicates are handled If you add the same element again: HashMap checks the bucket using hashCode() Then calls equals() to compare keys Since the key already exists, HashMap does not replace it, because the value (PRESENT) is the same HashSet simply ignores the duplicate add() returns false The set remains unchanged ➡️ Unlike HashMap, where the value gets replaced for duplicate keys. --- 4️⃣ Collision handling Same behavior as HashMap: First a linked list inside the bucket If a bucket grows to 8 or more elements (and capacity ≥ 64), it converts into a Red-Black Tree for faster lookup If elements reduce later, it may convert back into a list --- 5️⃣ Iteration When you loop through a HashSet: for (E e : set) { ... } You’re actually iterating through the keys of the internal HashMap. --- 6️⃣ Null handling HashSet allows one null value, because HashMap allows one null key. It is stored in bucket 0. --- 7️⃣ Time complexity Average insert / search / delete → O(1) Worst case → O(log n) (tree), or O(n) (linked list) --- 💡 In short: HashSet uses HashMap internally Your element becomes the key A dummy object becomes the value Duplicates are ignored, not overwritten All HashMap rules (hashing, buckets, collisions) apply underneath Simple design, very efficient. #Java #HashSet #HashMap #CollectionsFramework #BackendDevelopment #CodingConcepts #CleanCode
To view or add a comment, sign in
-
🔥 Tricky Java / Production Bug — The ThreadLocal Memory Leak (a.k.a. The Silent Killer of Threads 😅) Picture this: You’re working at Microsoft, your microservice is running smooth as butter 🧈... until suddenly, memory usage starts climbing like it just got promoted 🚀 You open your monitoring dashboard — GC is running fine, no OutOfMemoryError yet... but the heap looks like it’s hoarding sessions from the Windows XP era 👀 Welcome to the sneaky world of ThreadLocal memory leaks 🧵 💡 The Sneaky Cause: You use ThreadLocal to store request-specific data (user info, correlation ID, transaction state). But you forget the golden rule: threadLocal.remove(); Your thread pool reuses threads — and guess what stays behind? 👉 Old values. Since ThreadLocalMap keeps weak keys but strong values, once the key is GC’ed, the value just… hangs there. Forever. Leaking memory byte by byte 💀 🧠 Example: ThreadLocal<UserContext> context = new ThreadLocal<>(); void process(UserContext ctx) { context.set(ctx); // Business logic here... context.remove(); // 🧹 Mandatory cleanup! } 🔍 Debugging Tips (When You Suspect ThreadLocal Trouble): 1️⃣ Use a heap dump tool like Eclipse MAT or VisualVM — search for ThreadLocalMap. 2️⃣ Look for “unreachable” keys with large retained sizes. 3️⃣ Check if threads in the pool are holding references to old request objects. 4️⃣ Enable GC logs or use a memory profiler — rising heap after GC = red flag 🚩 5️⃣ Watch for “slow leaks” — this one creeps up over hours or days, not minutes. 🧾 Quick Checklist for Safe ThreadLocal Usage: ✅ Always call remove() after use. ✅ Avoid storing heavy objects (like sessions, big collections). ✅ Prefer request-scoped beans or dependency injection where possible. ✅ Review all ThreadLocal usage before deploying to prod. ✅ Don’t assume frameworks will clean it up for you — they won’t 😏 🎯 Final Thought: ThreadLocal is like caffeine ☕ — great in moderation, disastrous when overused. Use it smartly, clean it up religiously. Otherwise, your memory leak will show up in the next sprint review saying: > “Hi, I’m still here… and I brought more heap!” 😜 #Java #SpringBoot #ThreadLocal #MemoryLeak #Microsoft #TrickyInterviewQuestion #BackendEngineering #Concurrency #Debugging #ProductionBug #JavaDeveloper #CodingHumor
To view or add a comment, sign in
-
🚀 Solving Binary WebSocket Challenges in Java + Spring Boot Recently, while implementing a real-time WebSocket app, I ran into a subtle but important challenge with binary messages. ✅ The Problem: ------------------ Sending text messages works fine: session.sendMessage(new TextMessage(payload)); But binary messages (like numbers or files) cannot be sent directly like text. Reusing the same ByteBuffer for multiple sends caused partial or corrupted messages, and using the sender’s session in a broadcast loop sent messages only back to the sender. 🔧 How I Solved It: --------------------- Server-side: =========== byte[] bytes = new byte[payload.remaining()]; payload.get(bytes); // Broadcast to all users safely for (WebSocketSession userSession : userSessionMap.values()) { if (userSession.isOpen()) { userSession.sendMessage(new BinaryMessage(ByteBuffer.wrap(bytes))); // new buffer each time } } Why this matters: ----------------- ByteBuffer position changes after read → must create a new buffer for each send. Use userSession.sendMessage(), not session.sendMessage(), to broadcast to all users. Client-side: ========== ws.binaryType = "arraybuffer"; // receive binary as ArrayBuffer const view = new DataView(event.data); const value = view.getUint32(0, false); // read numeric value correctly ws.binaryType = "arraybuffer" tells the browser how to handle incoming binary data. DataView ensures you read the exact number/value sent from the server. 💡 Key Takeaways: =================== Binary data requires careful handling on both server and client sides. Small details like buffer reuse and proper client interpretation can make or break real-time apps. Solving these edge cases gave me deeper insight into Java NIO, WebSocket protocols, and frontend-backend integration. #Java #SpringBoot #WebSocket #BinaryData #RealTime #FullStack #ProblemSolving #TechnicalSkills #mohacel #mohacelhosen
To view or add a comment, sign in
-
-
🧹 What is a Garbage Collector? In Java, the Garbage Collector (GC) automatically manages memory for you. It finds objects that your code no longer uses and frees up that memory. Sounds boring? 😐 Okay — let’s make it interesting! 🚀 💡 G1 Garbage Collector — the Modern Hero Since Java 9, the G1 Garbage Collector has been the default GC in most Java distributions. Why? Because it offers high performance, predictable pause times, and smart memory management — all at once. 🏗️ G1 GC Architecture — the Core Concepts G1 GC is built on a few powerful ideas: Generational Region-based Parallel Mostly Concurrent Stop-the-world (STW) Evacuating Let’s break down what these actually mean (no buzzwords, just clarity 👇). 🧬 Generational G1 follows the weak generational hypothesis — most objects die young. So it divides the heap into two main areas: Young Generation → newly created objects (Eden + Survivor spaces) Old Generation → objects that have survived several GC cycles Example: Person person = new Person(); This person object is created in the Young region. 🧩 Region-Based & Incremental Design Instead of one big contiguous heap, G1 divides memory into many equal-sized regions (1–32 MB each). This allows G1 to collect regions incrementally — reclaiming only parts of the heap that need cleanup, reducing pause times. 🧠 Remembered Sets & Write Barriers To track cross-region references (like when an old object references a young one), G1 uses: Remembered Sets (RSet) → data structures that track which regions reference others Write Barriers → tiny pieces of code the JVM inserts to update RSets when references change ⚙️ Parallel and Concurrent Phases G1 uses multiple threads to perform GC tasks (parallel) and runs some parts concurrently with your application. Advantages: ✅ Reduced pause time ✅ Scales to large heaps Trade-offs: ⚠️ Slightly higher CPU overhead ⚠️ Lower throughput compared to simpler collectors ⏸️ Stop-the-World (STW) Even though G1 is concurrent, some phases (like object evacuation) are stop-the-world events. That means all application threads pause briefly while G1 reclaims memory. The good news: G1 aims to keep those pauses short and predictable, and you can tune them 🚚 Evacuating (Compacting the Heap) G1 reclaims space by moving live objects from one region to another — this is called evacuation. Here’s how: New objects go into Eden. Surviving objects move to Survivor regions. Older survivors eventually move to the Old regions. 🧱 Humongous Objects Larger Objects are allocated in special regions outside the normal young/old flow. G1 handles them carefully — it doesn’t move them often, and only reclaims those regions when no live references remain. 💡 Pro Tip: If you’re getting frequent OutOfMemoryError and your heap contains very large objects (e.g., 17 MB JSON blobs or arrays), You know where to debug. #Java #JVM #GarbageCollection #G1GC #JavaPerformance #MemoryManagement #JavaDeveloper #JavaCore
To view or add a comment, sign in
-
Java secrets --- Post 1: Java ka "Zero-Day Feature" - 1995 se chupa hua raaz!🤯 #Java #ProgrammingSecrets #Coding ```java // Java 1.0 ka woh feature jo documentation mein kabhi nahi aaya: static { System.out.println("Static block - main() se pehle!"); } public static void main(String[] args) { System.out.println("Main method!"); } // Output: // Static block - main() se pehle! // Main method! ``` Kyun? Static blocks class load hote hi execute hote hain! Ye feature 1995 se exist karta hai par 99%developers ko nahi pata! 💀 --- Post 2: Java ka "Time Travel" - Code future mein execute karo!⚡ #Java #Developer #CodingTips ```java public class TimeTravel { public static void main(String[] args) { // \u000d System.out.println("Ye line 2005 mein execute hogi!"); // Unicode character Java compiler ko force karta hai // line break karne ko - time travel effect! 🕰️ } } ``` Secret: Unicode characters compile-time pe process hote hain! Java creators ne ye feature intentionally nahi banaya tha!🔥 --- Post 3: Java ka "Quantum Entanglement" - Do variables ek saath change!🌌 #Java #Programming #TechSecrets ```java public class QuantumJava { static int a = 10; static int b = a; // Entangled! public static void main(String[] args) { a = 20; System.out.println(b); // 10 ❌ Not entangled! // Java variables actually entangled nahi hote // Par developers sochte hain hote hain! 😂 } } ``` Reality Check: Java mein primitive assignment copy karta hai, reference nahi! Ye misconception 80%beginners ko hota hai! 💡 --- Post 4: Java ka "Parallel Universe" - Same class different behavior!🚀 #Java #JVM #Programming ```java public class ParallelJava { public static void main(String[] args) throws Exception { ClassLoader cl1 = new CustomClassLoader(); ClassLoader cl2 = new CustomClassLoader(); Class<?> c1 = cl1.loadClass("MyClass"); Class<?> c2 = cl2.loadClass("MyClass"); System.out.println(c1 == c2); // false ✅ // Same class name, different universe! // Different classloaders = different classes! 🌍 } } ``` JVM Magic: Har classloader ek alag "universe" create karta hai! Ye advanced concept 1%Java developers ko pata hai! 💪
To view or add a comment, sign in
-
🚀“Threads Made Simple: Understanding ExecutorService in Java” Have you ever written something like this? 👇 new Thread(() -> processTask()).start(); new Thread(() -> sendEmail()).start(); new Thread(() -> generateReport()).start(); It works… but what happens when you have hundreds of tasks running? Your app might start too many threads, consume memory, and even slow down the system. That’s where ExecutorService comes in — the smarter way to manage multithreading in Java. 🚀 🧩 What is ExecutorService? ExecutorService is part of java.util.concurrent and acts like a thread manager. Instead of manually creating and starting threads, it uses a thread pool — a group of reusable threads that efficiently execute your tasks. ⚙️ Example 1: Using a Fixed Thread Pool Let’s say you have 10 tasks to run, but only want 3 threads working at once: public class ExecutorExample { public static void main(String[] args) { // Create a thread pool of fixed size (3 threads) ExecutorService executor = Executors.newFixedThreadPool(3); // Submit tasks for execution executor.submit(() -> processTask()); executor.submit(() -> sendEmail()); executor.submit(() -> generateReport()); // Always shut down the executor after tasks are done executor.shutdown(); } } 🧠 What happens here? 👉Creates 3 reusable threads. 👉Adds each task to a queue for execution — the pool reuses existing threads instead of creating new ones. 👉Gracefully stops the executor after completing all tasks. You save memory and improve performance by reusing threads. ✅ Why We Use ExecutorService 1. 🧵 Thread Reuse: No need to create a new thread for every task. 2. 🔒 Control: Easily start, stop, or limit concurrent threads. 3. ⚡ Performance: Thread pooling avoids overhead from frequent thread creation. 4. 💥 Error Handling: Exceptions can be tracked and managed using Future. 5. 🧠 Clean Code: Focus on what tasks to execute — not how to manage threads. #Java #Concurrency #ExecutorService #Multithreading #SpringBoot #CodingBestPractices #JavaDeveloper
To view or add a comment, sign in
-
Java ke woh secrets jo accidentally discover hue the! 🔥 --- Post 1: Java ka "Accidental Recursive Generics" bug!🤯 ```java public class QuantumBug<T extends QuantumBug<T>> { // Ye pattern originally Eclipse IDE ke internal code mein tha // Josh Bloch ne accidentally discover kiya tha! public T getSelf() { return (T) this; // ClassCastException kabhi nahi aayegi! } } // Usage: class MyClass extends QuantumBug<MyClass> { } // Ye recursive generic bound Java designers ne intentionally nahi banaya tha! ``` Secret: Ye pattern Java Collections Framework mein Enum<E extends Enum<E>> ke liye use hota hai! 💀 --- Post 2: Java ka "Double Colon Operator" ka internal hack!🔥 ```java public class DoubleColonMagic { public static void main(String[] args) { // System::exit actually yeh hai: // (args) -> System.exit(args) // Par internally Java yeh karta hai: // invokedynamic #0:accept:(Ljava/lang/invoke/MethodHandles$Lookup; // Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodHandle; // Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite; // Method reference ka bytecode directly lambda se different hai! } } ``` Compiler Accident: Method references lambdas se fundamentally different compile hote hain! 💡 --- Post 3: Java ka "Interface Private Methods" ka hidden conflict!🚀 ```java public interface PrivateMethodConflict { private void secret() { System.out.println("Private in interface - Java 9+"); } // Java designers ko ye add karte waqt pata nahi tha ki: // 1. Ye inheritance mein participate nahi karte // 2. Par fir bhi default methods inhe call kar sakte hain // 3. Ye diamond problem ko complicate karte hain! default void useSecret() { secret(); // ✅ Chalega - par ye design decision controversial tha! } } ``` Design Conflict: Java team 2 saal tak debate karti rahi private interface methods ko add karne se pehle! 💪 --- Post 4: Java ka "Boolean Array" ka memory layout paradox!🔮 ```java public class BooleanArrayParadox { public static void main(String[] args) { boolean[] arr = new boolean[1000]; // Boolean array actually 1 byte per element use karta hai // Na ki 1 bit! - Ye performance optimization ke liye kiya gaya System.out.println("Memory: " + java.lang.management.ManagementFactory.getMemoryMXBean() .getHeapMemoryUsage().getUsed()); // Boolean[] (object array) vs boolean[] (primitive array) // dono ka memory layout different hai! } } ``` Performance Accident: Boolean arrays 1 byte use karte hain kyunki bit manipulation slow hoti hai! 💀 --- yeh accidental discoveries Java team ko bhi surprise karti hain! 😎
To view or add a comment, sign in
-
🧑🎓Mastering Java: Try-With-Resources 🧑💻 Use try-with-resources to write cleaner, safer code! No more messy finally blocks — resources like files, DB connections, or streams close automatically. In Java, managing resources like files, database connections, or streams properly is crucial — 🚫if not closed, they can lead to memory leaks or file locks. That’s where try-with-resources comes in! 🧠 What it is: try-with-resources (introduced in Java 7) is a feature that automatically closes resources after use — no need for a finally block! ✅ Any class that implements AutoCloseable (like FileReader, BufferedReader, Connection, etc.) can be used inside it. 💡 Example: import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class TryWithResourcesExample { public static void main(String[] args) { // The resource declared inside try() will be auto-closed try (BufferedReader reader = new BufferedReader(new FileReader("data.txt"))) { String line; while ((line = reader.readLine()) != null) { System.out.println(line); } } catch (IOException e) { System.out.println("Error reading file: " + e.getMessage()); } // No need for finally block to close the reader! } } 🔍 Why it’s better than traditional try-catch-finally Before Java 7: BufferedReader reader = null; try { reader = new BufferedReader(new FileReader("data.txt")); // process file } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } Now: Just one clean block! ✅ ⚙️ Key Benefits: *Automatically closes resources *Cleaner and more readable code *Avoids resource leaks *Works with multiple resources (try (res1; res2)) #Java #SpringBoot #CleanCode #CodingBestPractices #JavaDeveloper
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