2828import java .util .concurrent .CompletableFuture ;
2929import java .util .concurrent .CompletionException ;
3030import java .util .concurrent .CompletionStage ;
31+ import java .util .concurrent .ConcurrentLinkedQueue ;
3132import java .util .concurrent .atomic .AtomicReference ;
3233
3334import static java .util .Collections .emptyList ;
@@ -332,9 +333,8 @@ private CompletableFuture<List<V>> dispatchQueueBatch(List<K> keys, List<Object>
332333 return CompletableFuture .completedFuture (values );
333334 }
334335
335- List <K > clearCacheKeys = new ArrayList <>();
336- var batchLoaderScheduler = loaderOptions .getBatchLoaderScheduler ();
337- CompletableFuture <Void >[] scheduledCompletions = new CompletableFuture [keys .size ()];
336+ Collection <K > clearCacheKeys = new ConcurrentLinkedQueue <>();
337+ List <Runnable > completeValueRunnables = new ArrayList <>();
338338 for (int idx = 0 ; idx < queuedFutures .size (); idx ++) {
339339 K key = keys .get (idx );
340340 V value = values .get (idx );
@@ -360,14 +360,17 @@ private CompletableFuture<List<V>> dispatchQueueBatch(List<K> keys, List<Object>
360360 future .complete (value );
361361 }
362362 };
363- if (batchLoaderScheduler != null ) {
364- scheduledCompletions [idx ] = batchLoaderScheduler .scheduleCompletion (completeValueRunnable , key , value );
365- } else {
366- scheduledCompletions [idx ] = CompletableFutureKit .run (completeValueRunnable );
367- }
363+ completeValueRunnables .add (completeValueRunnable );
364+ }
365+ CompletableFuture <Void > result ;
366+ var batchLoaderScheduler = loaderOptions .getBatchLoaderScheduler ();
367+ if (batchLoaderScheduler != null ) {
368+ result = batchLoaderScheduler .scheduleCompletions (completeValueRunnables , keys , values );
369+ } else {
370+ result = CompletableFuture .allOf (completeValueRunnables .stream ().map (CompletableFutureKit ::run ).toArray (CompletableFuture []::new ));
368371 }
369372 // Wait for all completions to return
370- return allOf ( scheduledCompletions ) .thenApply (ignored -> {
373+ return result .thenApply (ignored -> {
371374 possiblyClearCacheEntriesOnExceptions (clearCacheKeys );
372375 return values ;
373376 });
@@ -392,7 +395,7 @@ private void assertResultSize(List<K> keys, List<V> values) {
392395 assertState (keys .size () == values .size (), () -> "The size of the promised values MUST be the same size as the key list" );
393396 }
394397
395- private void possiblyClearCacheEntriesOnExceptions (List <K > keys ) {
398+ private void possiblyClearCacheEntriesOnExceptions (Collection <K > keys ) {
396399 if (keys .isEmpty ()) {
397400 return ;
398401 }
0 commit comments