@@ -162,12 +162,21 @@ Object getCacheKeyWithContext(K key, Object context) {
162
162
163
163
DispatchResult <V > dispatch () {
164
164
boolean batchingEnabled = loaderOptions .batchingEnabled ();
165
- //
166
- // we copy the pre-loaded set of futures ready for dispatch
167
- final List <K > keys = new ArrayList <>();
168
- final List <Object > callContexts = new ArrayList <>();
169
- final List <CompletableFuture <V >> queuedFutures = new ArrayList <>();
165
+ final List <K > keys ;
166
+ final List <Object > callContexts ;
167
+ final List <CompletableFuture <V >> queuedFutures ;
170
168
synchronized (dataLoader ) {
169
+ int queueSize = loaderQueue .size ();
170
+ if (queueSize == 0 ) {
171
+ lastDispatchTime .set (now ());
172
+ return emptyDispatchResult ();
173
+ }
174
+
175
+ // we copy the pre-loaded set of futures ready for dispatch
176
+ keys = new ArrayList <>(queueSize );
177
+ callContexts = new ArrayList <>(queueSize );
178
+ queuedFutures = new ArrayList <>(queueSize );
179
+
171
180
loaderQueue .forEach (entry -> {
172
181
keys .add (entry .getKey ());
173
182
queuedFutures .add (entry .getValue ());
@@ -176,8 +185,8 @@ DispatchResult<V> dispatch() {
176
185
loaderQueue .clear ();
177
186
lastDispatchTime .set (now ());
178
187
}
179
- if (!batchingEnabled || keys . isEmpty () ) {
180
- return new DispatchResult <>( completedFuture ( emptyList ()), 0 );
188
+ if (!batchingEnabled ) {
189
+ return emptyDispatchResult ( );
181
190
}
182
191
final int totalEntriesHandled = keys .size ();
183
192
//
@@ -524,4 +533,11 @@ private CompletableFuture<List<V>> setToValueCache(List<V> assembledValues, List
524
533
}
525
534
return CompletableFuture .completedFuture (assembledValues );
526
535
}
536
+
537
+ private static final DispatchResult <?> EMPTY_DISPATCH_RESULT = new DispatchResult <>(completedFuture (emptyList ()), 0 );
538
+
539
+ @ SuppressWarnings ("unchecked" ) // Casting to any type is safe since the underlying list is empty
540
+ private static <T > DispatchResult <T > emptyDispatchResult () {
541
+ return (DispatchResult <T >) EMPTY_DISPATCH_RESULT ;
542
+ }
527
543
}
0 commit comments