'Modifying List contained in Object inside ConcurrentHashMap
I am using a Map to store customer's basket items in-memory. My map has the following signature Map<Integer, Basket> customerBaskets = new ConcurrentHashMap<>();
Each Basket class has a list of items defined as Collection<Item> items = new ArrayList<>().
During the app startup all the customers loaded into the map and an empty basket is assigned to them. Now I would like to add items to the customer's basket in a thread-safe manner.
Since ConcurrentHashMap reads are not locking, I could get the Basket based on customerId and freely add items to the items list, this doesn't guarantee me thread safety. How can I ensure thread-safety for writes to this list and reads have the latest written value? Please advise.
Thank You.
Solution 1:[1]
You need either to synchronize the read-write operations on the ArrayList using something like ReentrantLock or use CopyOnWriteArrayList implementation for this underlying array.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ALVO |
