나는 자바 8 병렬 스트림에 대해 배우려고합니다. 먼저 Executor를 사용하고 병렬 스트림을 사용하여 코드 아래에 작성했습니다. Executor 접근 (5 초)만큼 병렬 스트림이 두 번 (10 초) 소요됩니다. 제 생각에는 병렬 스트림도 비슷한 성능을 보여야합니다. 병렬 스트림이 두 배의 시간이 걸리는 이유는 무엇입니까? 내 컴퓨터에는 8 개의 코어가 있습니다.자바 8 병렬 스트림 더 많은 시간이 걸립니다
/**
*
*/
package com.shashank.java8.parallel_stream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/**
* @author pooja
*
*/
public class Sample {
public static int processUrl(String url) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Running Thread " + Thread.currentThread());
return url.length();
}
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
usingExecutor();
usingParallelStream();
}
public static void usingParallelStream() {
Date start = new Date();
// TODO Auto-generated method stub
int total = buildUrlsList().parallelStream().mapToInt(Sample::processUrl).reduce(0, Integer::sum);
Date end = new Date();
System.out.println(total);
System.out.println((end.getTime() - start.getTime())/1000);
}
public static void usingExecutor() throws Exception {
Date start = new Date();
ExecutorService executorService = Executors.newFixedThreadPool(100);
List<Future> futures = new ArrayList<>();
for (String url : buildUrlsList()) {
futures.add(executorService.submit(() -> processUrl(url)));
}
// iterate through the future
int total = 0;
for (Future<Integer> future : futures) {
total += future.get();
}
System.out.println(total);
Date end = new Date();
System.out.println((end.getTime() - start.getTime())/1000);
}
public static List<String> buildUrlsList() {
return Arrays.asList("url1", "url2", "url3", "url4", "url5", "url6", "url7", "url8", "url9");
}
}
정보를 다른 프로세스로 이동하는 데 시간이 걸릴 수 있습니다. 프랑스 음식을 먹기 위해 프랑스로 날아 가지 않을 것입니다. 데이터를 복사하는 데 많은 시간을 소비하고 실제 작업을 수행하는 데 충분한 시간을 소비하지 않습니다. –
글쎄, 그것은 * 당신 * 벤치 마크 * 벤치마킹 *에 관한 것입니다. 여기를 보셔야합니다 : http://stackoverflow.com/questions/504103/how-do-i-write-a-correct-micro-benchmark-in-java. – Eugene
우리는'Sample :: processUrl'이 무엇을하고 있는지 전혀 알지 못하기 때문에 정말로 도움이되지 않습니다. 그러나 8 코어 머신에서 100 개의 스레드를 가진'ExecutorSerivce'가 전혀 좋지 않다는 것이 명백해진다. – Eugene