While building a recent Spring Boot application, I realized... The Hook: Stop defaulting to .parallelStream() to make your Java code "faster." 🛑 The Insight: It’s a common misconception that parallel streams always improve performance. Under the hood, parallelStream() uses the common ForkJoinPool. If you are executing CPU-intensive tasks on a massive dataset, it’s great. But if you are doing I/O operations (like database calls or network requests) inside that stream, you will exhaust the thread pool and bottleneck your entire application. The Pro Tip: Always benchmark. For I/O bound tasks, look into asynchronous programming (like CompletableFuture) or Java 21's Virtual Threads instead of parallel streams. #Java #PerformanceOptimization #SoftwareEngineering #CleanCode
Avoid Parallel Streams for I/O Operations in Java
More Relevant Posts
-
Java just quietly changed how servers handle millions of requests. And most developers haven't noticed yet. I'm talking about Virtual Threads — introduced in Java 21 (LTS). 🧵 Before Virtual Threads: → 1 request = 1 OS thread → OS threads are expensive (~1MB stack each) → 10,000 requests = system struggling → The only fix was reactive programming (complex, hard to debug) After Virtual Threads: → Millions of virtual threads, managed by the JVM → Blocking a virtual thread doesn't block an OS thread → Write simple, readable blocking code — JVM handles the rest → No reactive spaghetti needed How easy is it to use? Thread.ofVirtual().start(() -> handleRequest(req)); Spring Boot 3.2+ supports it out of the box. Set spring.threads.virtual.enabled=true and you're done. This is Project Loom — years in the making. Production-ready right now. If your team is still on Java 8 or 11 — it's time to have that upgrade conversation. Have you tried Virtual Threads yet? Drop your experience below 👇 #Java #Java21 #VirtualThreads #ProjectLoom #BackendDevelopment #SpringBoot
To view or add a comment, sign in
-
-
Most Java developers write code that "talks to the internet" without realizing where in the network stack it actually lives. Here's a simple breakdown 👇 🔵 Layers 1 & 2 (Physical & Data Link) — Java doesn't operate here. The OS and hardware take care of this. 🟡 Layer 3 (Network) — Java uses InetAddress to work with IP addresses and DNS. 🟠 Layer 4 (Transport) — Socket for TCP, DatagramSocket for UDP. This is where Java "connects." 🔴 Layer 5 & 6 (Session & Presentation) — SSL/TLS handshakes via javax.net.ssl, and data serialization using ObjectMapper or ObjectOutputStream. 🟢 Layer 7 (Application) — Java's home turf! Spring Boot, HttpClient, JavaMail, WebSockets — all live here. 💡 As a beginner, start at Layer 7 and work your way down. The deeper you go, the better developer you become! Which layer surprised you the most? 👇 #Java #Networking #OSIModel #BeginnerDeveloper #JavaDeveloper #Programming
To view or add a comment, sign in
-
-
Continuing my recent posts on JVM internals and performance, today I’m sharing a look at Java 21 Virtual Threads (from Project Loom). For a long time, Java handled concurrency using platform threads (OS threads)—which are powerful but expensive, especially for I/O-heavy applications. This led to complex patterns like thread pools, async programming, and reactive frameworks to achieve scalability. With Virtual Threads, Java introduces a lightweight threading model where thousands (even millions) of threads can be managed efficiently. 👉 When a virtual thread performs a blocking I/O operation, the underlying carrier (platform) thread is released to do other work. This brings Java closer to the efficiency of event-loop models (like in Node.js), while still allowing developers to write simple, synchronous code without callback-heavy complexity. However, in real-world scenarios, especially when teams migrate from Java 8/11 to Java 21, it’s important to keep a few things in mind: • Virtual Threads are not a silver bullet—they primarily improve I/O-bound workloads, not CPU-bound ones • If the architecture is not aligned, you may not see significant latency improvements • Legacy codebases often contain synchronized blocks or locking, which can lead to thread pinning and reduce the benefits of Virtual Threads Project Loom took years to evolve because it required deep changes to the JVM, scheduling, and thread management—while preserving backward compatibility and Java’s simplicity. Sharing a diagram that illustrates: • Platform threads vs Virtual Threads • Carrier thread behavior • Pinning scenarios Curious to hear—are you exploring Virtual Threads in your applications, or still evaluating? 👇 #Java #Java21 #VirtualThreads #ProjectLoom #Concurrency #Performance #SoftwareEngineering
To view or add a comment, sign in
-
-
Day 65 - DSA Practice Solved LeetCode 237 – Delete Node in a Linked List. The catch is you don’t get the head or the previous node, so the usual deletion approach doesn’t work. Instead, copy the value from the next node and link to the node after it. This effectively removes the given node. Simple problem, but a good reminder to think differently when constraints block the obvious approach. #DSA #LeetCode #Java
To view or add a comment, sign in
-
-
The interesting timeout question is not whether a distributed system will hit deadlines. It will. The real question is what your code does next. Do you fail the whole response? Do you return partial data? Do you stop unfinished work cleanly, or let it keep running after the caller is already gone? That is what I wrote about in Part 2 of the structured concurrency series. In Java 21, `StructuredTaskScope` makes those choices much more explicit. You can model strict all-or-nothing timeouts, or return partial results when some sections are optional. The part I like is that cancellation and cleanup stop being scattered across the code. This post covers: - all-or-nothing timeout handling - partial results with explicit missing sections - why `joinUntil(...)` is only part of the design - why `scope.shutdown()` matters when returning early - what test cases are worth adding for timeout-sensitive endpoints Article: https://lnkd.in/gWCm5UzB #Java #StructuredConcurrency #ProjectLoom #Java21 #DistributedSystems #BackendEngineering
To view or add a comment, sign in
-
🚀 Think Java Garbage Collection is just “automatic memory cleanup”? Think again. Behind the scenes, Java offers multiple Garbage Collectors, each designed for different performance needs. Here’s a quick breakdown 👇 🔹 Serial GC – Simple, single-threaded (good for small apps) 🔹 Parallel GC – Multi-threaded, high throughput (default in many cases) 🔹 CMS (Concurrent Mark-Sweep) – Low pause times, but now deprecated 🔹 G1 GC (Garbage First) – Balanced performance, predictable pauses (widely used) 🔹 ZGC – Ultra-low latency (pause times in milliseconds) 🔹 Shenandoah GC – Concurrent GC with minimal pause times 💥 Each GC is a trade-off between: 👉 Throughput 👉 Latency (pause time) 👉 Memory footprint ⚡ Quick Tip: Don’t just stick with the default GC. For most modern backend systems, G1 GC or ZGC can significantly improve performance depending on your latency needs. Java isn’t slow… it’s all about how well you tune it. #Java #GarbageCollection #Performance #BackendEngineering #JVM
To view or add a comment, sign in
-
I just answered Stack Overflow question! A developer was building an Auction System in Java and was struggling with concurrency issues while placing bids. He used synchronized and asked — "Is this good enough or should I use Locks?" Here's what I suggested 🔴 Problem with synchronized: → Locks the entire method → Becomes bottleneck under high traffic ✅ Better Approaches: → Use ReentrantLock with tryLock() for better thread control → Use AtomicReference for price updates → Use BlockingQueue for high concurrency — zero race conditions His logic was perfect, just needed a better locking mechanism! Still learning Java basics but being able to help someone in the community hits different 🙌 #Java #StackOverflow #Concurrency #Programming #CodingJourney #Developer #OpenSource
To view or add a comment, sign in
-
-
Spring Boot Circular Proxy Issue — Advanced trap 🤯 Even if you FIX circular dependency… Spring may still create proxies internally. 👉 This can lead to: ❌ Unexpected behavior ❌ Method not executing correctly 💡 Why? Spring uses AOP proxies (JDK / CGLIB) ⚠️ Problem: Internal method calls bypass proxy Example: Method A → calls Method B internally 👉 AOP (like @Transactional) won’t apply 🔥 Solution: ✔ Move logic to another bean ✔ Avoid internal method calls 👉 This is why some transactions “don’t work” Understanding proxies = senior-level Spring knowledge 💯 #SpringBoot #Java #AOP
To view or add a comment, sign in
-
Ever been confused about what "Platform Independent" really means for Java? This infographic provides the clearest answer I've seen. Is Java Platform Independent? YES. But here is the crucial distinction that often gets overlooked: Java is Platform-Independent, while the JVM is Platform-Dependent. This is the core magic behind "Write Once, Run Anywhere." As the diagram perfectly visualizes, it's a two-step process: Step 1: Compilation Your Java Source Code (.java file) is compiled by javac into universal, platform-neutral Java Bytecode (.class file). This Bytecode is the single, universal binary. Step 2: Run Anywhere (The Key) This same single Bytecode file can then travel to any platform. BUT, for it to execute, that specific platform must have its own platform-specific Java Virtual Machine (JVM). The universal Bytecode goes into a JVM for Windows. The universal Bytecode goes into a JVM for macOS. The universal Bytecode goes into a JVM for Linux. The JVM acts as the final translator (an abstraction layer), taking that neutral Bytecode and converting it into the native machine instructions of that specific hardware and operating system. It's a powerful separation of concerns: you write and compile your code once, and the JVM handles the last-mile translation for any device. Did you have a clear understanding of this distinction? 👇 Let me know what other tech concepts are often misunderstood in the comments. #Java #SoftwareEngineering #JavaDeveloper #TechEducation #JVM #Programming #PlatformIndependence #TechStack #ComputerScience
To view or add a comment, sign in
-
-
Your Spring Boot app has 200 users waiting. Your CPU is at 10%. No errors. No crashes. The culprit? 20 threads — all blocked, all doing nothing. I built a benchmark project to see exactly what happens inside the JVM when a classic thread pool hits this wall, and what changes when Java 21 virtual threads take over. Same app. Same business logic. One executor swap. Results with 200 concurrent users over 30 seconds: → Throughput: 1.95 req/s (classic) vs 252.89 req/s (loom) → p(95) latency: 56 seconds (classic) vs 0.81 seconds (loom) → Requests completed: 117 (classic) vs 7,784 (loom) → 140 users never got a response in classic mode. In Loom, all 200 finished cleanly with zero interruptions. What surprised me most was not the throughput number. It was looking inside the JVM mid-load and seeing 1,846 virtual threads active while the OS thread count barely moved. Loom does not add OS threads — it parks tasks as objects on the heap and frees the carrier thread instantly. One non-obvious gotcha for anyone adopting this in production: Thread.getAllStackTraces() intentionally excludes virtual threads in Java 21. Your existing monitoring tools may already be blind to them. Full benchmark with thread snapshots, heap data, GC numbers, and code walkthrough in the article below. #Java #Java21 #ProjectLoom #SpringBoot #BackendDevelopment #SoftwareEngineering #Programming
To view or add a comment, sign in
More from this author
Explore related topics
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