🚀 Java Deep Dive — Daemon Threads (Something many developers overlook) In Java, not all threads behave the same way. There are two types: • User Threads • Daemon Threads The JVM keeps running as long as at least one user thread is alive. But daemon threads work differently. They are background service threads used for supporting tasks like: • Garbage Collection • Monitoring • Background cleanup If all user threads finish, the JVM will terminate immediately, even if daemon threads are still running. Example: Java Example Thread thread = new Thread(() -> { while(true){ System.out.println("Running..."); } }); thread.setDaemon(true); thread.start(); If the main thread finishes, this daemon thread will not keep the JVM alive. Important rule: You must call "setDaemon(true)" before starting the thread, otherwise Java throws "IllegalThreadStateException". 💡 Key Insight Daemon threads are useful for background tasks that should not block application shutdown. #Java #Multithreading #BackendDevelopment #SoftwareEngineering #LearningInPublic
Java Daemon Threads: Understanding JVM Behavior
More Relevant Posts
-
Day 7 of #100DaysOfCode — Java is getting interesting ☕ Today I explored the Java Collections Framework. Before this, I was using arrays for everything. But arrays have one limitation — fixed size. 👉 What if we need to add more data later? That’s where Collections come in. 🔹 Key Learnings: ArrayList grows dynamically — no size worries Easy operations: add(), remove(), get(), size() More flexible than arrays 🔹 Iterator (Game changer) A clean way to loop through collections: hasNext() → checks next element next() → returns next element remove() → safely removes element 🔹 Concept that clicked today: Iterable → Collection → List → ArrayList This small hierarchy made everything much clearer. ⚡ Array vs ArrayList Array → fixed size ArrayList → dynamic size Array → stores primitives ArrayList → stores objects Still exploring: Set, Map, Queue next 🔥 Consistency is the only plan. Showing up every day 💪 If you’re also learning Java or working with Collections — let’s connect 🤝 #Java #Collections #ArrayList #100DaysOfCode #JavaDeveloper #LearningInPublic
To view or add a comment, sign in
-
Something weird happened while I was debugging a Java program today. I had a simple program running with multiple threads, and I printed the thread names just to see what was happening. The output looked something like this: main http-nio-8080-exec-1 http-nio-8080-exec-2 ForkJoinPool.commonPool-worker-3 At first I ignored it. But then I started wondering… Where are all these threads actually coming from? I didn’t create them. After digging a bit deeper, I realized something interesting. Modern Java applications are constantly using different thread pools behind the scenes. For example: • The web server creates request threads • "CompletableFuture" uses the ForkJoinPool • Some frameworks create background worker threads • The JVM itself runs internal service threads Which means even a “simple” backend service may actually be running dozens of threads at the same time. It made me realize something: A lot of complexity in backend systems isn’t in the code we write — it’s in the systems running around our code. Now I’m a lot more curious about what’s actually happening inside the JVM when our apps run. #Java #BackendEngineering #SpringBoot #SoftwareEngineering #LearningInPublic
To view or add a comment, sign in
-
Tackling the "Silent Overflow" in Java 🛑🔢 I recently worked through LeetCode #7: Reverse Integer, and it was a fantastic deep dive into how Java handles 32-bit integer limits and the dangers of "silent overflows." The Problem: Reverse the digits of a signed 32-bit integer. If the reversed number goes outside the 32-bit signed range of [-2^{31}, 2^{31} - 1], the function must return 0 The "Asymmetry" Challenge: In Java, Integer.MIN_VALUE is -2,147,483,648, while Integer.MAX_VALUE is 2,147,483,647. The negative range is one unit larger than the positive range due to Two's Complement arithmetic. This creates a massive trap: using Math.abs() on the minimum value will actually overflow and remain negative! My Optimized Solution Strategy: I implemented a two-pronged approach to handle these edge cases efficiently: 1️⃣ Pre-emptive Boundary Filtering: I added a specific optimization check at the very beginning: if(x >= Integer.MAX_VALUE - 4 || x <= Integer.MIN_VALUE + 6) return 0;. This catches values at the extreme ends of the 32-bit range immediately, neutralizing potential Math.abs overflow before the main logic even begins. 2️⃣ 64-bit Buffering: I used a long data type for the reversal calculation. This provides a 64-bit "safety net," allowing the math to complete so I can verify if the result fits back into a 32-bit int boundary. Complexity Analysis: 🚀 Time Complexity: O(log_10(n))— The loop runs once for every digit in the input (at most 10 iterations for any 32-bit integer). 💾 Space Complexity: O(1)— We use a constant amount of extra memory regardless of the input size. Small details like bit-range asymmetry can break an entire application if ignored. This was a great reminder that as developers, we must always think about the physical limits of our data types! #Java #LeetCode #SoftwareDevelopment #ProblemSolving #Algorithms #CleanCode #JavaProgramming #DataStructures #CodingLife
To view or add a comment, sign in
-
-
Blog: Some Benefits of Enabling Compact Object Headers in Java 25 for Streams There are signs. You just have to learn how to look for and read them. https://lnkd.in/e4ARCGbQ
To view or add a comment, sign in
-
I’ve written a simple blog breaking down the real difference between blocking, parking, and virtual threads in Java — and explaining what exactly gets paused (OS thread vs continuation) when your code “waits.” https://lnkd.in/g5DxUNMW
To view or add a comment, sign in
-
🧠 JVM Memory & Garbage Collection Let me explain Java memory using your HOUSE as an example 🏠👇 🏠 JVM = Your House Your Java app lives here. Different rooms, different purposes. 📦 Heap = The Storeroom All objects go here. Never clean it? It crashes → OutOfMemoryError 💥 Heap has sections: 👶 Young Gen → new stuff (dies fast) 🧓 Old Gen → stuff you kept for years 🏷️ Metaspace → labels about your stuff 🪑 Stack = Your Desk Small, fast. Holds current work (method calls, local variables). Cleans itself when work is done. No GC needed! 🧹 Garbage Collection = Mom Cleaning Your Room “Do you still need this? No? GONE.” Java finds unused objects and removes them automatically. But sometimes GC yells: “EVERYBODY FREEZE while I clean!” ⏸️ These Stop-the-World pauses make apps laggy. 🔧 Choose Your Cleaner: 🟢 G1 → good all-rounder 🔵 ZGC → almost zero pauses 🟡 Shenandoah → low-latency beast 🔴 Serial → tiny apps only 📝 String Pool = Shared Notebook String a = “Hello”; String b = “Hello”; Java keeps ONE copy. Both point to it. Memory saved! 🎯 ⚡ Make Your App Faster: → Create only objects you need → Set unused objects to null → Close DB connections always → Remove unused listeners → Tune heap with -Xms and -Xmx → Profile with VisualVM or JConsole 🚨 Memory Leak Culprits: ❌ Unclosed DB connections ❌ Static lists that grow forever ❌ Listeners never unsubscribed ❌ Huge data in user sessions 🎯 Recap: 🏠 JVM = House 📦 Heap = Storeroom 🪑 Stack = Desk 🧹 GC = Auto cleaner 📝 String Pool = Shared notebook 🚨 Leaks = Stuff you forgot to toss Clean heap = Fast app 🏃💨 #Java #JVM #GarbageCollection #HeapMemory #JavaDeveloper #Programming #CodingTips #SoftwareEngineering #LearnJava #DevCommunity #100DaysOfCode #JavaPerformance #MemoryManagement #CleanCode #JavaInterview #BackendDevelopment
To view or add a comment, sign in
-
Day 5 – Java Stream Practice | Finding Duplicate Characters Today I worked on finding duplicate characters in a string using Java Streams. Problem: Given a string, identify characters that appear more than once. Approach: Removed spaces from the string Converted characters into a stream using chars() Used Collectors.groupingBy() along with counting() to calculate frequency Filtered characters with count greater than 2 This exercise helped me strengthen my understanding of: Stream transformations (chars(), mapToObj()) Frequency counting using grouping operations Writing clean and functional-style Java code Sample Input: I Love Java Output: Duplicate characters along with their frequency Consistently practicing Java Streams is improving my approach to data processing and problem solving. #Java #100DaysOfCode #JavaStreams #ProblemSolving #CodingJourney
To view or add a comment, sign in
-
-
🚀 **Day 4/30 – LeetCode Java Challenge** Today’s problem pushed me to think beyond basic comparisons and focus on **pattern-based validation**. Worked on a string problem where the key insight was separating characters based on **even and odd indices**, then comparing frequency distributions instead of direct string matching. 📊 **Result:** ✔️ Accepted (752/752 test cases) ⚡ Runtime: 5 ms (Beats 93.81%) 💾 Memory: Efficient (Beats 86.60%) 💡 **What actually mattered today:** * Brute force thinking won’t scale — pattern recognition does * Breaking a problem into smaller logical groups simplifies everything * Frequency arrays can outperform more complex data structures when used correctly Let’s be real: This wasn’t a hard problem, but the approach matters. If you miss the pattern, you overcomplicate it. If you see it early, the solution becomes clean and efficient. Day 4 done. Still building consistency, still sharpening fundamentals. Archana J E Bavani k Deepika Kannan Divya Suresh Hari priya B Devipriya R Harini B Bhavya B Kezia H Vaishnavi Janaki #LeetCode #Java #DSA #ProblemSolving #Consistency #30DaysOfCode
To view or add a comment, sign in
-
-
A lot of Java backend work eventually turns into thread math. How many threads, how much memory, how much blocking, when to switch to async. Java 21 shipped with Project Loom, and this part of Java finally started getting simpler instead of more complicated. It felt less like a new abstraction and more like Java fixing an old pain. What I like about virtual threads (primary feature of Project Loom) is that they let you keep straightforward blocking code for I/O-heavy work without running into the same limits so quickly. When a virtual thread blocks, it parks and frees the carrier thread. That is the part that really changes things. I have written Part 1 of my Project Loom series covering: - Why platform threads reach a ceiling. - How M:N scheduling operates. - A comparison of platform threads versus virtual threads in code. - The advantages and limitations of virtual threads. I also added a small NoteSensei chat to the article. Still experimenting with it. You can ask questions about the post, or try a short quiz if you want to check whether the ideas actually stuck. Let me know whether it is useful or just noise. https://lnkd.in/gbJfcnUG #Java #ProjectLoom #VirtualThreads #BackendEngineering #Java21 #Concurrency #SoftwareEngineering
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