We receive messages from different sources like JMS, AMQP, EventBus and try to process them quickly. Multithreading with Thread Pool can help us to do that.

When Performance Is the Main Consideration

In the microservices world, we receive messages from different sources like JMS, AMQP, EventBus and try to process them as quickly as possible. Multithreading with Thread Pool can help us to do that.

But if we want to treat messages of the same categories (same users, same products…) in the order we receive them, it could get more complicated.

When Order Is Necessary

This sample code shows that an ExecutorThreadPool does not treat messages in the right order for categories 1 and 2:

Java

public class Main {
    public static final int NB_MSG = 5;
    public static final int TASK_DURATION = 500;
    public static void main(String[] args) throws InterruptedException {
        ThreadPoolNotOrdered threadPool = new ThreadPoolNotOrdered();
        new Main().executeInThreadPool(threadPool);
        Thread.sleep(NB_MSG * TASK_DURATION + 1_000);
        threadPool.shutdown();
    }

    private void executeInThreadPool(ThreadPool threadPool) {
        for (int i = 0; i < NB_MSG; i++) {
            executeForUser(threadPool, "CATEGORY_1", i);
            executeForUser(threadPool, "CATEGORY_2", i);
        }
    }
    private void executeForUser(ThreadPool threadPool, String userUuid, int i) {
        Message message = new Message(userUuid, i);
        threadPool.execute(message, () -> {
            System.out.println("Start task  => " + message);
            try {
                Thread.sleep(TASK_DURATION);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("End of task => " + message);
        });

    }
}
public class ThreadPoolNotOrdered {
    private final ExecutorService executorService = Executors.newFixedThreadPool(4);
    public void execute(Message message, Runnable runnable) {
        executorService.submit(runnable);
    }

    public void shutdown() {

        executorService.shutdown();
    }
}

#java #microservices #microservice #java microservices #message processing

Processing Messages in Order With CompletableFuture
1.10 GEEK