惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

C
Check Point Blog
Y
Y Combinator Blog
GbyAI
GbyAI
Microsoft Azure Blog
Microsoft Azure Blog
Martin Fowler
Martin Fowler
博客园_首页
大猫的无限游戏
大猫的无限游戏
美团技术团队
S
SegmentFault 最新的问题
T
The Blog of Author Tim Ferriss
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
MyScale Blog
MyScale Blog
小众软件
小众软件
Vercel News
Vercel News
阮一峰的网络日志
阮一峰的网络日志
N
Netflix TechBlog - Medium
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
量子位
博客园 - 【当耐特】
J
Java Code Geeks
F
Fortinet All Blogs
宝玉的分享
宝玉的分享
Stack Overflow Blog
Stack Overflow Blog
博客园 - 司徒正美

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Stop the Traffic Jam: Handling Blocking Calls in Spring B...
realNameHidd · 2026-04-29 · via DEV Community

realNameHidden

Learn how to handle blocking calls in a non-blocking Spring Boot app using Project Reactor. Master the publishOn and subscribeOn operators with Java 21 examples.

Stop the Traffic Jam: Handling Blocking Calls in Spring Boot WebFlux

Imagine you’re at a high-end fast-food joint. The cashier (our Event Loop) is lightning-fast at taking orders. They don’t wait for the burger to cook; they just take the order, hand you a buzzer, and move to the next person. This is how Spring Boot WebFlux stays so fast.

But what happens if a customer asks the cashier to personally go into the back and hand-grind the beef for ten minutes? The line stops. Everyone waits. The "fast" system is now broken.

In the world of Java programming, that hand-grinding is a blocking call (like a legacy database query or a slow external API). If you do it on the Event Loop, your entire application grinds to a halt. Today, we’re going to learn how to delegate those slow tasks so your app stays snappy.

Core Concepts: The "Waiting Room" Strategy

In a non-blocking system, we use a small number of threads to handle thousands of requests. If one thread gets stuck waiting for an I/O response, it’s a disaster. To fix this, we use the Scheduler concept.

Think of a Scheduler as a separate "Waiting Room" with its own staff. When a blocking task arrives, the Event Loop hands it off to this specialized staff, stays free to take more orders, and asks to be notified when the task is done.

Why do we need this?

  • Legacy Integration: Not every database driver (like JDBC) or API is reactive yet.
  • CPU Intensive Tasks: Heavy calculations can "block" the thread just as much as I/O does.
  • Better Resource Usage: It prevents your application from crashing under high load by isolating "heavy" work.

Code Examples (Java 21)

To follow along, ensure you have the spring-boot-starter-webflux dependency in your project. We will use Schedulers.boundedElastic(), which is specifically designed for wrapping blocking code.

1. The Service Layer: Wrapping the Block

In this example, we simulate a slow JDBC call. We use Mono.fromCallable() and shift the execution to a different thread pool using .subscribeOn().

import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;
import org.springframework.stereotype.Service;
import java.time.Duration;

@Service
public class LegacyDataService {

    // Simulating a blocking database call (e.g., JDBC)
    public String getLegacyData() {
        try {
            Thread.sleep(2000); // Artificial 2-second delay
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        return "Data from the stone age!";
    }

    // Wrapping the blocking call in a Non-Blocking way
    public Mono<String> getRemoteDataReactive() {
        return Mono.fromCallable(() -> getLegacyData())
                .subscribeOn(Schedulers.boundedElastic()); 
                // subscribeOn moves the WHOLE task to a separate thread pool
    }
}

Enter fullscreen mode Exit fullscreen mode

2. The Controller: Exposing the Endpoint

Now, let's create a RestController to trigger this.

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;

@RestController
public class DataController {

    private final LegacyDataService service;

    public DataController(LegacyDataService service) {
        this.service = service;
    }

    @GetMapping("/api/data")
    public Mono<String> fetchData() {
        return service.getRemoteDataReactive()
                .map(data -> "Processed: " + data);
    }
}

Enter fullscreen mode Exit fullscreen mode

Testing the Setup

Once your Spring Boot application is running on port 8080, you can test it using the following CURL command. Even though the "database" takes 2 seconds, the Event Loop remains free to handle other incoming requests during that wait!

Request:

curl -X GET http://localhost:8080/api/data

Enter fullscreen mode Exit fullscreen mode

Response (after 2 seconds):

Processed: Data from the stone age!

Enter fullscreen mode Exit fullscreen mode

Best Practices for Non-Blocking Apps

To keep your Java programming clean and efficient, follow these rules:

  1. Use boundedElastic for Blocking I/O: Never use Schedulers.parallel() for blocking calls. parallel() is for CPU-heavy tasks; boundedElastic() is designed to grow and shrink to handle blocking threads.
  2. Isolate the Block: Wrap the blocking call as close to the source as possible. Don't let blocking logic "leak" into your main controller logic.
  3. Avoid block() at all costs: Calling .block() inside a WebFlux application is like slamming the brakes on a highway. It defeats the purpose of the entire framework.
  4. Monitor Thread Pools: Use tools like Micrometer to keep an eye on your boundedElastic pool size. If it's always full, you might need to optimize your underlying legacy systems.

Conclusion

Learning how to handle blocking calls in a non-blocking Spring Boot application is the "secret sauce" to building resilient, high-performance systems. By offloading heavy lifting to the right Schedulers, you ensure your app stays responsive, no matter how slow your legacy dependencies might be.

If you want to dive deeper into the technical specs, I highly recommend checking out the official Project Reactor Documentation or the Oracle Java Documentation for the latest on Java 21 virtual threads.

Ready to try it out? Try converting one of your existing blocking services to this reactive pattern and see how the throughput improves!

Call to Action

Did this analogy help you understand Schedulers? Do you have a tricky blocking scenario you're trying to solve? Drop a comment below or ask a question—I’d love to help you learn Java more effectively!