Skip to main content

Command Palette

Search for a command to run...

Thread Pool Concept , MultiThreading in SpringBoot

Updated
3 min read

step 1 : Configure the executor bean.

@EnableAsync : @EnableAsync is a Spring Framework annotation used to enable asynchronous processing support in a Spring Boot application. When you use this annotation, Spring will create a thread pool and manage the execution of methods annotated with @Async in a separate thread.

@Configuration
@EnableAsync
public class AsyncConfig {
@Bean(name ="multithreadingdemobean")
    public Executor taskExecutor(){
       ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
       executor.setCorePoolSize(2);           // Set the initial number of threads in the pool.
       executor.setMaxPoolSize(2);            // Set the maximum number of threads that can be created in the pool.
       executor.setQueueCapacity(100);        // Set the maximum number of tasks that can be queued if all threads are busy.
       executor.setThreadNamePrefix("demo"); // Set the prefix for the names of threads created by this executor.
       executor.initialize();  //Initialize the ThreadPoolTaskExecutor:
       return executor; 
 } 
}

step 2: Performing multithreading : let it be simple for now lets have we have a lot of string and our job is to find their length and this is how we achieved using multithreading concept by calling executor bean.

  @Async("multithreadingdemobean")
    public void processTask(String payload) {
        log.info("Starting Thread - Processing Payload {}",payload );
        log.info("Length of Payload string is {}", payload.length());
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("Exiting Thread - Processing payload {} completed", payload);

    }

Spring Batch: to read data in MultiThreaded way in spring batch

Using CompletableFuture with ExecutorService allows you to efficiently process API responses in batches, handle timeouts, and compose complex workflows in your Java Spring Boot application.

In this example, we use CompletableFuture.runAsync() to process each batch asynchronously in the thread pool

CompletableFuture.runAsync()-->is a method from the CompletableFuture class in Java. It is used to asynchronously run a given task in the background without returning any result.

Demo code:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class ApiBatchProcessor {

  private final Executor taskExecutor;

    @Autowired
    public MyService(@Qualifier("multithreadingdemobean") Executor taskExecutor) {
        this.taskExecutor = taskExecutor;
    }

    public void processApiResponses(List<Response> apiResponses) {
        int batchSize = 50; // Adjust the batch size as needed

        for (int i = 0; i < apiResponses.size(); i += batchSize) {
            List<Response> batch = apiResponses.subList(i, Math.min(i + batchSize, apiResponses.size()));

            // Process each batch asynchronously using CompletableFuture
            CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(() -> {
                for (Response response : batch) {
                    apiService.processResponse(response);
                }
            }, threadPoolExecutor);
        }
    }
}

For example, let's say you have 1000 names, and you are processing them in batches of 50. If you have a thread pool with 5 threads, the processing will happen in the following way:

  1. Thread 1: Processes names 1 to 50 (batch 1).

  2. Thread 2: Processes names 51 to 100 (batch 2).

  3. Thread 3: Processes names 101 to 150 (batch 3).

  4. Thread 4: Processes names 151 to 200 (batch 4).

  5. Thread 5: Processes names 201 to 250 (batch 5).

These batches will be processed concurrently, meaning that each thread will handle its batch independently and not wait for the others to finish. This allows for efficient use of CPU cores and resources, making the processing faster compared to sequential processing.

More from this blog

NEHA JAIN

11 posts