Quadratic time complexity means runtime grows as O(N²). A hidden repeated scan can make apparently concurrent code catastrophically slow: calling indexOf inside a grouping operation scans the list for every account. section 7.1.2
Concurrency that loses to repeated scanning
With 10,000 accounts, the indexOf-based grouping performs tens of millions of redundant comparisons. A custom benchmark measured concurrent execution at 30,398 ms, compared with 25 ms for the single-threaded version. section 7.1.2
public Optional<Account> accountParallel(Integer id) {
return accounts.parallelStream().filter(v -> v.getId().equals(id)).findAny(); #A
}
private final ExecutorService executor =
Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
public Optional<Account> accountConcurrent(Integer id) { #B
int chunkSize = Math.max(1, accounts.size() /
Runtime.getRuntime().availableProcessors());
List<CompletableFuture<Optional<Account>>> futures =
accounts.stream()
.collect(Collectors.groupingBy(account ->
accounts.indexOf(account) / chunkSize))
.values()
.stream()
.map(chunk -> CompletableFuture.supplyAsync(() ->
chunk.stream().filter(v ->
v.getId().equals(id)).findAny(), executor))
.collect(Collectors.toList());
return futures.stream()
.map(CompletableFuture::join)
.filter(Optional::isPresent)
.findFirst()
.orElse(Optional.empty());
}
public Optional<Account> accountOptimized(Integer id) { #C
ForkJoinPool customThreadPool = new
ForkJoinPool(Runtime.getRuntime().availableProcessors());
try {
return customThreadPool.submit(() ->
accounts.parallelStream().filter(v ->
v.getId().equals(id)).findAny()).get();
} catch (Exception e) {
throw new RuntimeException("Error in parallel processing", e);
} finally {
customThreadPool.shutdown();
}
}
public List<Optional<Account>> findMultipleAccounts(List<Integer> ids) {
#D
return ids.parallelStream()
.map(this::accountParallel)
.collect(Collectors.toList());
}Inspect the accountConcurrent implementation to see how indexOf inside groupingBy introduces the repeated scan. section 7.1.2






