I have to improve a process that is currently sequential, and i wanna make it multi-thread. This process uses Spring JPA, with spring boot 2 and java 17.
I would like to have a feedback on the following mock-up and see if I can improve something, or there are errors.
The exportOrder()
method is the one that contains the business logic. What happens is:
- Validates the object
- Maps OrdrDesc to ObjectA
- Stores ObjectA (Different database then OrdrDesc)
- Updates OrdrDesc
- If ObjectA was stored, maps OrdrDesc to ObjectB
- Stores ObjectB (Different database then OrdrDesc, but same as ObjectA)
Here is the code of the thread handling.
void test2() {
final LinkedBlockingQueue<OrdrDesc> queue = new LinkedBlockingQueue<>();
ExecutorService executorService = Executors.newFixedThreadPool(10);
List<OrdrDesc> orders = getOrders(); // calls db - returns around 50k records
for (OrdrDesc ordrDesc : orders) {
try {
queue.put(ordrDesc);
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // set interrupt flag
System.out.println("Failed to consume order: " + ordrDesc);
}
}
Runnable consumer = () -> {
while (!Thread.currentThread().isInterrupted() || !queue.isEmpty()) {
OrdrDesc ordrDesc = queue.poll();
if (ordrDesc != null) {
exportOrder(ordrDesc);
}
}
};
while (!queue.isEmpty()) {
executorService.execute(consumer);
}
}