동시성(Concurrency)과 병렬성(Parallelism)

포크조인(ForkJoin) 프레임워크

forkjoin
ForkJoin

병렬 스트림 생성

MaleMember maleMember = totalList.parallelStream()
  .filter(m -> m.getSex() == Member.Sex.MALE)
  .collect(MaleMember::new, MaleMember::accumlate, MaleMemer::combine);

병렬 처리 성능

public class Example {
  public static final int SLEEP_VAL = 100; // 작을수록 순차 처리가 빠름

  public static void work(int value) {
    try {
      Thread.sleep(SLEEP_VAL);
    } catch (InterruptedException e) {
    }
  }

  // 순차 처리
  public static long testSequencial(List<Integer> list) {
    long start = System.nanoTime();
    
    list.stream().forEach((a) -> work(a));

    long end = System.nanoTime();
    return end - start;
  }

  // 병렬 처리
  public static long testParallel(List<Integer> list) {
    long start = System.nanoTime();
    
    list.stream().parallel().forEach((a) -> work(a));

    long end = System.nanoTime();
    return end - start;
  }


  public static void main(String[] args) {
    List<Integer> list = Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);

    long time1 = testSequencial(list);
    long time2 = testParallel(list);
  }
}
public class Example {
  public static final int SLEEP_VAL = 10;

  public static void work(int value) {
  }

  // 병렬 처리
  public static long testParallel(List<Integer> list) {
    long start = System.nanoTime();
    
    list.stream().parallel().forEach((a) -> work(a));

    long end = System.nanoTime();
    return end - start;
  }


  public static void main(String[] args) {
    List<Integer> arrayList = new ArrayList<>();
    List<Integer> linkedList = new LinkedList<>();

    for(int i = 0; i < 1_000_000; ++i) {
      arrayList.add(i);
      linkedList.add(i);
    }

    // warm up
    long time1 = testParallel(arrayList);
    long time2 = testParallel(linkedList);

    time1 = testParallel(arrayList);
    time2 = testParallel(linkedList);
  }
}