The problem: I have a ViewModel base class that has a HashMap to store the ViewModel's property values. However I'm encountering an intermittent bug where a read from this collection (on a seperate thread) is returning null directly after an item was added.
private HashMap<String, Serializable> _propertyValues = new HashMap<String, Serializable>();
An Example: I want to fetch user information when a user id is provided to the ViewModel.
ViewModel wires up to PropertyChanged for UserID. The property changed handler creates a background thread to pull the values. The background thread reads the UserID and then fetches from the server.
What we're seeing is that in some rare cases the background thread is reading null from the property hashmap (thread 2), directly after the value was provided (thread 1).
My Thoughts: I suspect this to be due to data visibility and the absence of a thread safe collection. When reviewing thread safe options I came across:
- Hashtable - Seems the community considers this out dated and discourages its use.
- ConcurrentHashMap - Seems like I could still run into my issue due to this lacking reliable synchronization
- Collections.synchronizedMap(map) - Seems particular in how you use it, not sure if it has benefits over Hashtable
At this time I feel like Hashtable is what I'll want, but could use confirmation. :)
Use Cases:
- 100ish reads all at once, every minute or so.
- Frequent writes from the UI thread
- Periodic reads from background threads that need accurate values. Background thread read, right after a UI thread write.
Thanks, Trey