Java 8 (LTS) · Topic 9 of 12
Parallel streams
Definition​
A parallel stream splits the work across several CPU cores. It can speed up heavy calculations on large data, but it adds overhead, so it is slower for small lists. Never use it for blocking calls or with shared mutable state.
Example code​
Same result, computed on several cores
import java.util.stream.LongStream;
class Demo {
static boolean isPrime(long n) {
if (n < 2) return false;
for (long i = 2; i * i <= n; i++) if (n % i == 0) return false;
return true;
}
public static void main(String[] args) {
long sequential = LongStream.rangeClosed(1, 200_000).filter(Demo::isPrime).count();
long parallel = LongStream.rangeClosed(1, 200_000).parallel().filter(Demo::isPrime).count();
System.out.println(sequential + " primes (one core)");
System.out.println(parallel + " primes (many cores)"); // same answer, because each check is independent
}
}
// Output:
// 17984 primes (one core)
// 17984 primes (many cores)
Finished this page? Track your progress (saved only in your browser).