Skip to content
Advertisement

Locking execution within CompletableFuture

I need to post-process result of CompletableFuture.supplyAsync execution to get intermediate result. My code looks following

JavaScript

In a result I’m facing with java.util.concurrent.CompletionException: java.lang.IllegalMonitorStateException on .thenAccept(resultPerBatch -> { line

Seems like I’m using lock in wrong way but I cannot figure out how to avoid this kind of exception.

Advertisement

Answer

There’s no guarantee that the Function passed to thenApply and the Consumer passed to thenAccept will execute on the same thread.

In this case, there is no need to separate them into separate steps:

JavaScript

However, it is probably a better idea to process this data in batches rather than trying to create so many threads. This will ultimately either run out of memory, out of available native threads, or reject work because the queue is full.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement