How to prevent IllegalStateException in reactor when you need to block

Viewed 55

We have a synchronous process that needs to call two REST endpoints, whereas the result of the first is needed for the second. Using Springs WebClient the .block() causes the following exception:

java.lang.IllegalStateException: block()/blockFirst()/blockLast() are blocking, which is not supported in thread parallel-2

How can this be prevented?

Here is a simplified code snippet:

var job = webClient.createJob().block();
if (job == null || StringUtils.isBlank(job.getId())) {
    throw new Exception("WebClient did not return with a job id");
}
batchRecords(job.getId(), records);// does some additional calls to the webClient

This works in the unit test, but when called through a @RestController the above exception is thrown.

EDIT: The batchRecords method currently also has blocking Monos in it, so we can have a delay in between:

public void batchRecords(final String jobId, final List<InventoryRecord> records)
    var recordCount = 0;
    var inventoryPositions = new ArrayList<InventoryPosition>();
    var recordIterator = records.iterator();
    while (recordIterator != null && recordIterator.hasNext()) {
        var inventoryRecord = recordIterator.next();
        inventoryPositions.add(mapInventoryPosition(inventoryRecord));
        recordCount++;
        if (inventoryPositions.size() == batchSize) {
            var response = createBatch(jobId, inventoryPositions);
            Thread.sleep(sleepTime);
            response.block();
            inventoryPositions = new ArrayList<>();
        }
    }
}
1 Answers

You should do it reactively without blocking:

webClient.createJob()
    .filter(job -> !StringUtils.isBlank(job.getId()))
    .flatMap(job -> batchRecords(job.getId(), records))
    .switchIfEmpty(Mono.error(new Exception("WebClient did not return with a job id")));

As soon as the createJob operation is finished, the result is filtered and provided to the flatMap operator. In case of an empty response (Mono.empty()) an exception is thrown.

Related