// 순차적 소수 계산
static long pi(long n) {
return LongStream.rangeClosed(2, n)
.mapToObj(BigInteger::valueOf)
.filter(i -> i.isProbablePrime(50))
.count();
}
// 병렬 소수 계산
static long piParallel(long n) {
return LongStream.rangeClosed(2, n)
.parallel()
.mapToObj(BigInteger::valueOf)
.filter(i -> i.isProbablePrime(50))
.count();
}
// 잘못된 병렬화 예시 (응답 불가 상태 발생 가능)
Stream.iterate(BigInteger.ONE, n -> n.add(BigInteger.ONE))
.parallel()
.map(p -> p.isProbablePrime(50))
.limit(20)
.forEach(System.out::println);
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;
public class ParallelStreamDemo {
public static void main(String[] args) {
// 대규모 데이터 준비 (1천만 개)
List<Integer> bigList = IntStream.rangeClosed(1, 10_000_000)
.boxed()
.collect(ArrayList::new, ArrayList::add, ArrayList::addAll);
// 간단한 연산 (합계)
System.out.println("간단한 연산 (합계):");
Instant start = Instant.now();
long sum = bigList.stream().mapToLong(i -> i).sum();
System.out.println("순차 처리: " + Duration.between(start, Instant.now()).toMillis() + "ms");
start = Instant.now();
long sumParallel = bigList.parallelStream().mapToLong(i -> i).sum();
System.out.println("병렬 처리: " + Duration.between(start, Instant.now()).toMillis() + "ms");
// 복잡한 연산 (소수 판별)
System.out.println("\n복잡한 연산 (소수 판별):");
start = Instant.now();
long primeCount = bigList.stream()
.limit(100_000)
.filter(ParallelStreamDemo::isPrime)
.count();
System.out.println("순차 처리: " + Duration.between(start, Instant.now()).toMillis() + "ms");
start = Instant.now();
long primeCountParallel = bigList.parallelStream()
.limit(100_000)
.filter(ParallelStreamDemo::isPrime)
.count();
System.out.println("병렬 처리: " + Duration.between(start, Instant.now()).toMillis() + "ms");
}
// 소수 판별 메서드 (계산 비용이 큰 연산)
static boolean isPrime(int n) {
if (n <= 1) return false;
if (n <= 3) return true;
if (n % 2 == 0 || n % 3 == 0) return false;
for (int i = 5; i * i <= n; i += 6) {
if (n % i == 0 || n % (i + 2) == 0) return false;
}
return true;
}
}