2017-09-07 3 views
2

동기화 된 블록에 메서드 정의를 넣지 않고 ConcurrentHashMap으로 해결할 수 있는지 궁금하십니까?업데이트를 잃지 않고 장바구니 업데이트

/** 
    Implement thread-safe updating of user's cart. 
    Exit criteria is carts is updated atomically, product is appended 
    in the end of cart. 
**/ 

void addToCart(ConcurrentHashMap<Integer, List<Integer>> carts, Integer userId, Integer productId) 

답변

0

다음과 같은 해결책이 효과적 일 수 있다고 생각하지만 제안을 환영합니다. 나는 thread safe list를 사용할 필요가 없다고 생각한다.

static void addToCart2(ConcurrentHashMap<Integer, List<Integer>> carts, Integer userId, Integer productId) { 
    carts.putIfAbsent(userId, new ArrayList<>()); 
    carts.computeIfPresent(userId, (userKey, listValue) -> { 
    listValue.add(productId); 
    return listValue; 
}); 

}

관련 문제