简体   繁体   English

Hashtable,ConcurrentHashMap和数据可见性

[英]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: 在查看线程安全选项时,我遇到了:

  1. Hashtable - Seems the community considers this out dated and discourages its use. Hashtable - 似乎社区认为这已过时并且不鼓励使用它。
  2. ConcurrentHashMap - Seems like I could still run into my issue due to this lacking reliable synchronization ConcurrentHashMap - 由于缺乏可靠的同步,我似乎仍然遇到了我的问题
  3. Collections.synchronizedMap(map) - Seems particular in how you use it, not sure if it has benefits over Hashtable Collections.synchronizedMap(map) - 特别是你如何使用它,不确定它是否比Hashtable有好处

At this time I feel like Hashtable is what I'll want, but could use confirmation. 这时我觉得Hashtable是我想要的,但可以使用确认。 :) :)

Use Cases: 用例:

  1. 100ish reads all at once, every minute or so. 100ish每分钟读一次,每分钟左右。
  2. Frequent writes from the UI thread 来自UI线程的频繁写入
  3. Periodic reads from background threads that need accurate values. 定期从需要准确值的后台线程中读取。 Background thread read, right after a UI thread write. 在UI线程写入后立即读取后台线程。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM