更新购物车而不会让更新丢失

时间:2017-09-07 17:28:52

标签: java java.util.concurrent concurrenthashmap

我不想将方法def放在同步块中,仍然想知道这是否可以用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) 

1 个答案:

答案 0 :(得分:0)

我认为以下解决方案可行,但我欢迎任何建议。我认为我不需要使用线程安全列表。

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;
});

}