我不想将方法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)
答案 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;
});
}