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

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

问题描述:

我不想将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) 

我在想下面的解决方案可能会工作,但我会欢迎任何建议。我不认为我需要使用线程安全列表。

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

}