Issue
I have a completable future code which throws NPE. I am unable to reproduce the exception in my local.
I have tried acceptance test and unit test for the code but it's not giving the exact error response.
final List<CompletableFuture<Map<K, V>>> completableFutures =
copy.stream()
.map(copy -> getRespForId(requestContext, copy))
.collect(Collectors.toList());
return CompletableFuture.allOf(completableFutures.toArray(new CompletableFuture<?>[0]))
.thenApply(future -> completableFutures.stream()
.map(CompletableFuture::join)
.flatMap(longMap -> longMap.entrySet().stream())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)));
Expected is
Caused by: java.util.concurrent.CompletionException: java.lang.NullPointerException
at java.base/java.util.concurrent.CompletableFuture.encodeThrowable(Unknown Source)
at java.base/java.util.concurrent.CompletableFuture.completeThrowable(Unknown Source)
at java.base/java.util.concurrent.CompletableFuture$UniApply.tryFire(Unknown Source)
at java.base/java.util.concurrent.CompletableFuture.postComplete(Unknown Source)
at java.base/java.util.concurrent.CompletableFuture.postFire(Unknown Source)
at java.base/java.util.concurrent.CompletableFuture$UniApply.tryFire(Unknown Source)
at java.base/java.util.concurrent.CompletableFuture$Completion.exec(Unknown Source)
at java.base/java.util.concurrent.ForkJoinTask.doExec(Unknown Source)
at java.base/java.util.concurrent.ForkJoinPool$WorkQueue.topLevelExec(Unknown Source)
at java.base/java.util.concurrent.ForkJoinPool.scan(Unknown Source)
at java.base/java.util.concurrent.ForkJoinPool.runWorker(Unknown Source)
at java.base/java.util.concurrent.ForkJoinWorkerThread.run(Unknown Source)
Caused by: java.lang.NullPointerException: null
at java.base/java.util.Objects.requireNonNull(Unknown Source)
at java.base/java.util.stream.Collectors.lambda$uniqKeysMapAccumulator$1(Unknown Source)
Solution
The problem here is not the keys but the values. You get this exception because a value is null. Looks like java.util.stream.Collectors#uniqKeysMapAccumulator
checks Objects.requireNonNull
on the values. See NullPointerException in Collectors.toMap with null entry values
Answered By - Sebastian
Answer Checked By - Robin (JavaFixing Admin)