[英]Hashtable, ConcurrentHashMap and Data Visibility
The problem: I have a ViewModel base class that has a HashMap to store the ViewModel's property values. 问题:我有一个ViewModel基类,它有一个HashMap来存储ViewModel的属性值。 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.
但是我遇到了一个间歇性的错误,在这个错误中,从这个集合中读取(在一个单独的线程上)在添加一个项目后直接返回null。
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提供用户标识时获取用户信息。
ViewModel wires up to PropertyChanged for UserID. ViewModel为UserID连接到PropertyChanged。 The property changed handler creates a background thread to pull the values.
属性更改处理程序创建一个后台线程来提取值。 The background thread reads the UserID and then fetches from the server.
后台线程读取UserID,然后从服务器获取。
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). 我们所看到的是,在极少数情况下,后台线程在提供值后直接从属性hashmap(线程2)读取null(线程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:
在查看线程安全选项时,我遇到了:
At this time I feel like Hashtable is what I'll want, but could use confirmation. 这时我觉得Hashtable是我想要的,但可以使用确认。 :)
:)
Use Cases: 用例:
Thanks, Trey 谢谢,特雷
ConcurrentHashMap will do just fine. ConcurrentHashMap会做得很好。 It has internal synchronization to prevent these sorts of problems.
它具有内部同步以防止出现这些问题。 It also has other methods that you may find helpful, such as
putIfAbsent
. 它还有其他您可能会发现有用的方法,例如
putIfAbsent
。
Its main disadvantage relative to Collections.synchronizedMap
is a larger memory footprint. 它相对于
Collections.synchronizedMap
主要缺点是更大的内存占用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.