A parallel stream processes pipeline elements concurrently across multiple CPU cores. Replacing stream() with parallelStream() is simple, but it is not automatically faster: measured results showed 63 ms versus 25 ms for single-threaded execution. section 7.1.2
Evaluate parallel streams against workload size, execution strategy, and measured results:
- Use parallelStream() for a concise parallel account search, with findAny() returning an arbitrary matching account. section 7.1.2
- Compare the shortcut with CompletableFuture chunking and a custom ForkJoinPool rather than assuming greater concurrency means better performance. section 7.1.2
- Benchmark representative data sizes with warm-up phases and result-consistency checks before accepting a performance claim. 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 AccountFinder implementations that contrast parallelStream() with manually partitioned CompletableFuture execution. section 7.1.2

