eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

1. Overview

In this tutorial, we’ll understand the smart batching pattern. We’ll first look at micro batching and its pros and cons, and then we’ll see how smart batching can alleviate its problems. We’ll also look at some examples of both patterns using simple Java data structures.

2. Micro Batching

We could consider micro batching as the base for the smart batching pattern. Although inferior, it’s the base on which we’ll build smart batching.

2.1. What Is Micro Batching?

Micro batching is an optimization technique for systems with workloads that consist of bursts of small tasks. Although they have a small computational overhead, they come with some kind of operation that supports a low amount of requests per second, for example, a write to an I/O device.

When we employ the micro batching pattern, we avoid processing incoming tasks individually. Instead, we aggregate them in a batch, and once it’s large enough, we process them together.

With this grouping technique, we can optimize resource utilization, especially when it comes to I/O devices. This approach helps us mitigate the latency introduced by handling bursts of small tasks one by one.

2.2. How Does It Work?

The simplest way to implement micro batching is to cache incoming tasks in a collection such as a Queue. Once the collection is over a certain size, dictated by the target system’s properties, we gather all tasks up to that limit and process them together.

Let’s create a minimal MicroBatcher class:

class MicroBatcher {
    Queue<String> tasksQueue = new ConcurrentLinkedQueue<>();
    Thread batchThread;
    int executionThreshold;
    int timeoutThreshold;

    MicroBatcher(int executionThreshold, int timeoutThreshold, Consumer<List<String>> executionLogic) {
        batchThread = new Thread(batchHandling(executionLogic));
        batchThread.setDaemon(true);
        batchThread.start();
        this.executionThreshold = executionThreshold;
        this.timeoutThreshold = timeoutThreshold;
    }

    void submit(String task) {
        tasksQueue.add(task);
    }

    Runnable batchHandling(Consumer<List<String>> executionLogic) {
        return () -> {
            while (!batchThread.isInterrupted()) {
                long startTime = System.currentTimeMillis();
                while (tasksQueue.size() < executionThreshold && (System.currentTimeMillis() - startTime) < timeoutThreshold) {
                    Thread.sleep(100);
                }
                List<String> tasks = new ArrayList<>(executionThreshold);
                while (tasksQueue.size() > 0 && tasks.size() < executionThreshold) {
                    tasks.add(tasksQueue.poll());
                }
                executionLogic.accept(tasks);
            }
        };
    }
}

Our batcher class has two important fields, tasksQueue, and batchThread.

As our Queue implementation, we select the ConcurrentLinkedQueue since it offers concurrent access and can grow as much as needed. This is where all submitted tasks reside. In our case, we represent them as simple String objects we provide as arguments to executionLogic that we define externally.

Additionally, our MicroBatcher has a dedicated Thread for batch handling. We must note that task submission and processing must be done in different threads. This decoupling is the most important part of latency minimization. This is because we let only one thread issue the slow requests while the rest can submit tasks as fast as needed since they aren’t blocked by the operation.

Finally, we define executionThreshold and timeoutThreshold. The first determines the number of tasks that must be buffered before we execute them. Its value depends on the target operation. For example, if we’re writing to a network device, the threshold should be equal to the max packet size. The second is the maximum amount of time we’ll wait for tasks to be buffered before we process them, even if executionThreshold hasn’t been reached.

2.3. Pros and Cons

We get many benefits by using the micro batcher pattern. First, it gives us increased throughput since tasks are submitted regardless of the state of execution, which means that our system is more responsive.

Additionally, by tuning the micro batcher, we can achieve proper utilization of the underlying resource (e.g., disk storage) and saturate it to the optimal level.

Finally, it conforms well to real-world traffic, which rarely is uniform and usually comes in bursts.

One of the most important cons of this implementation, however, is the fact that when the system isn’t under load, for example, at night, even a single request is forced to wait for the timeoutThreshold before being processed. This results in under-utilization of resources and, most importantly, a bad user experience.

3. Smart Batching

Enter smart batching, a modified version of micro batching. The difference is that we omit the timeoutThreshold and instead of waiting for the queue to fill up with tasks, we immediately execute any number of tasks up to executionThreshold.

With this simple change, we avoid the low traffic latency issue mentioned above while still keeping all the benefits of micro batching. The reason is that usually, the time it takes to process a batch of tasks is enough for the queue to fill up with the next batch. We thus have optimal resource usage and avoid blocking the execution of single tasks, in case that’s all that’s pending.

Let’s convert our MicroBatcher into SmartBatcher:

class SmartBatcher {
    BlockingQueue<String> tasksQueue = new LinkedBlockingQueue<>();
    Thread batchThread;
    int executionThreshold;
    boolean working = false;
    SmartBatcher(int executionThreshold, Consumer<List<String>> executionLogic) {
        batchThread = new Thread(batchHandling(executionLogic));
        batchThread.setDaemon(true);
        batchThread.start();
        this.executionThreshold = executionThreshold;
    }

    Runnable batchHandling(Consumer<List<String>> executionLogic) {
        return () -> {
            while (!batchThread.isInterrupted()) {
                List<String> tasks = new ArrayList<>(executionThreshold);
                while(tasksQueue.drainTo(tasks, executionThreshold) == 0) {
                    Thread.sleep(100);
                }
                working = true;
                executionLogic.accept(tasks);
                working = false;
            }
        };
    }
}

We changed three things in our new implementation. First, we removed timeoutThreshold. Second, we changed our Queue implementation to BlockingQueue. These support the drainTo() method, which works perfectly for our needs. Finally, we took advantage of this method to simplify our batchHandling() logic.

4. No-Batching vs. Batching Comparison

Let’s create an application class with a simple scenario to test the straightforward method against the batched approach:

class BatchingApp {
    public static void main(String[] args) throws Exception {
        final Path testPath = Paths.get("./test.txt");
        testPath.toFile().createNewFile();
        ScheduledExecutorService executorService = Executors.newScheduledThreadPool(100);
        Set<Future> futures = new HashSet<>();
        for (int i = 0; i < 50000; i++) {
            futures.add(executorService.submit(() -> {
                Files.write(testPath, Collections.singleton(Thread.currentThread().getName()), StandardOpenOption.APPEND);
            }));
        }
        long start = System.currentTimeMillis();
        for (Future future : futures) {
            future.get();
        }
        System.out.println("Time: " + (System.currentTimeMillis() - start));
        executorService.shutdown();
    }
}

We’ve selected a simple file write for the I/O operation. We create a test.txt file and write 50000 lines to it using 100 threads. Although the time displayed in the console will depend on the target hardware, here’s an example:

Time (ms): 4968

Even trying with different thread counts, the time still is around 4500 ms. It seems we’re hitting our hardware’s limit.

Let’s now switch to SmartBatcher:

class BatchingApp {
    public static void main(String[] args) throws Exception {
        final Path testPath = Paths.get("./testio.txt");
        testPath.toFile().createNewFile();
        SmartBatcher batcher = new SmartBatcher(10, strings -> {
            List<String> content = new ArrayList<>(strings);
            content.add("-----Batch Operation-----");
            Files.write(testPath, content, StandardOpenOption.APPEND);
        });

        for (int i = 0; i < 50000; i++) {
            batcher.submit(Thread.currentThread().getName() + "-1");
        }
        long start = System.currentTimeMillis();
        while (!batcher.finished());
        System.out.println("Time: " + (System.currentTimeMillis() - start));
    }
}

We added a finished() method to SmartBatcher to check when all tasks are finished:

boolean finished() {
    return tasksQueue.isEmpty() && !working;
}

Here’s the new time shown:

Time (ms): 1053

Even with executionThreshold of 10, we achieve a five-fold improvement. Increasing the threshold to 100 reduces the time to ~150 ms, almost 50 times faster than the simplistic approach.

As we can see, employing a simple technique that takes advantage of the underlying hardware characteristics can drastically boost our application performance. We should always keep in mind what our system is doing and the traffic it’s working with.

5. Conclusion

In this article, we had an overview of task batching techniques, specifically micro batching and smart batching. We saw potential use cases, the pros and cons of micro batching, and how smart batching can mitigate its shortcomings. Finally, we looked at a comparison between simple task execution and batched execution.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – LS – NPI (cat=Java)
announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

eBook Jackson – NPI EA – 3 (cat = Jackson)