Interview question
How do you use parallel streams in Java, and when should you avoid them? Java में parallel streams कैसे use करें, और कब avoid करना चाहिए?
Answer
parallelStream() splits the source data across multiple threads (using the common ForkJoinPool) to process elements concurrently, but it's only beneficial under specific conditions.
import java.util.stream.*;
List<Integer> numbers = IntStream.rangeClosed(1, 1_000_000)
.boxed()
.collect(Collectors.toList());
// Sequential stream - single thread
long sum1 = numbers.stream()
.mapToLong(Integer::longValue)
.sum();
// Parallel stream - splits work across multiple threads
long sum2 = numbers.parallelStream()
.mapToLong(Integer::longValue)
.sum();
// For large, CPU-bound, independent computations, this can be faster
// DANGER: parallel streams with STATEFUL or ORDER-DEPENDENT operations
List<Integer> results = Collections.synchronizedList(new ArrayList<>());
numbers.parallelStream().forEach(results::add);
// Works but order is NOT guaranteed - use forEachOrdered() if order matters
// DANGER: shared mutable state without synchronization causes race conditions
int[] counter = {0};
numbers.parallelStream().forEach(n -> counter[0]++); // UNSAFE - race condition!
System.out.println(counter[0]); // often less than 1,000,000, unpredictable
// When to AVOID parallel streams:
// - Small datasets (thread coordination overhead exceeds any benefit)
// - I/O-bound operations (parallel streams are meant for CPU-bound work)
// - Operations with side effects on shared mutable state
// - When maintaining element order matters and isn't handled explicitly
// When parallel streams HELP:
// - Large datasets with independent, CPU-intensive per-element work
// - Purely functional operations with no shared mutable state
long primeCount = numbers.parallelStream()
.filter(n -> isPrime(n)) // CPU-intensive, independent per element
.count();parallelStream() source data को कई threads (common ForkJoinPool के ज़रिए) में split करके concurrently process करता है, पर सिर्फ specific conditions में फायदेमंद है।
import java.util.stream.*;
List<Integer> numbers = IntStream.rangeClosed(1, 1_000_000)
.boxed()
.collect(Collectors.toList());
// Sequential stream
long sum1 = numbers.stream()
.mapToLong(Integer::longValue)
.sum();
// Parallel stream
long sum2 = numbers.parallelStream()
.mapToLong(Integer::longValue)
.sum();
// खतरा: shared mutable state के साथ race conditions
int[] counter = {0};
numbers.parallelStream().forEach(n -> counter[0]++); // UNSAFE!
System.out.println(counter[0]); // अक्सर 1,000,000 से कम
// Parallel streams AVOID करें जब:
// - Small datasets
// - I/O-bound operations
// - Shared mutable state पर side effects
// - Order matter करता हो
// Parallel streams फायदेमंद जब:
// - बड़े datasets, independent CPU-intensive काम
long primeCount = numbers.parallelStream()
.filter(n -> isPrime(n))
.count();Was this answer clear?