kok202
Parallel stream 과 Map

2020. 1. 7. 16:05[개발] 기록

1. parallelStream + forEach 로  HashMap 을 collect 하려할 경우 원하는 결과가 안나올 수 있다.

Map<Long, Data> dataIdMap = new HashMap<>();

events
    .parallelStream()
    .forEach(data -> {
        dataIdMap.put(data.getId(), data);
    });

HashMap 은 Thread safe 하지 않다.

 

해결법 1 : ConcurrentHashMap 을 사용한다.

해결법 2 : stream 을 사용한다.

Map<Long, Data> dataIdMap = new HashMap<>();

events
    .stream()
    .forEach(data -> {
        dataIdMap.put(data.getId(), data);
    });

해결법 3 : 자바 8의 collect 기능을 이용한다.

Map<Long, Data> dataIdMap = events
    .parallelStream()
    .collect(Collectors.toMap(
        data -> data.getId(),
        data -> data));

 

 

 

 

 

2. parallelStream 으로 TreeMap 을 collect 하려 할 경우 무한 루프를 만들 수도 있다.

TreeMap<Long, List<Data>> dataGroupByGroupId = events
    .parallelStream()
    .collect(Collectors.groupingBy(Data::getGroupId, TreeMap::new, toList()));

https://ivoanjo.me/blog/2018/07/21/writing-to-a-java-treemap-concurrently-can-lead-to-an-infinite-loop-during-reads/

 

Writing to a Java TreeMap concurrently can lead to an infinite loop during reads - ivo's awfully random tech blog

The java.util.TreeMap documentation warns that the underlying implementation for this Map is not synchronized — and thus it is not thread-safe. But have you ever wondered what happens if you ignore that warning and you write an application that concurrentl

ivoanjo.me

 

 

 

 

 

'[개발] 기록' 카테고리의 다른 글

카카오 페이 결제 흐름  (0) 2020.02.22
JsonTypeInfo, JsonSubTypes : 필드 값에 따라 파싱 타입 결정하기  (0) 2019.10.23
Already had POJO for id 에러  (0) 2019.08.05
mvn vs mvnw  (0) 2019.06.26
자바 8 Stream  (0) 2019.06.06