TreeMap-同步文档说明 [英] TreeMap - Synchronization Documentation Explanation

查看:68
本文介绍了TreeMap-同步文档说明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

TreeMap javadoc具有下面的部分,我不明白下面部分的最后一行.这是否意味着要创建锁并将地图修改逻辑移至同步块或其他所有块中.仅结构修改需要同步并且访问是线程安全的.

TreeMap javadoc has the below part and i could not understand the last line of the below part. Does it means to create a lock and move the map modification logic into a synchronized block or something else all together. Will only the structural modification requires synchronization and accessing is thread safe.

请注意,此实现未同步.

如果多个线程同时访问一个映射,并且至少有一个线程在结构上修改该映射,则必须在外部进行同步.(结构修改是添加或删除一个或多个映射的任何操作;仅更改与现有键相关联的值不是结构修改.)这通常是通过对自然封装了地图的某些对象进行同步来实现的.如果不存在这样的对象,则应该映射"映射.使用Collections.synchronizedSortedMap方法.

If multiple threads access a map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more mappings; merely changing the value associated with an existing key is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the map. If no such object exists, the map should be "wrapped" using the Collections.synchronizedSortedMap method.

推荐答案

基本上,Javadoc令人困惑,因为如果您完全修改地图(包括仅更改与现有键相关联的值时),您就想要在几乎所有情况下都可以同步所有操作.几乎不需要同步的唯一时间是,在发布地图之后,该地图是完全只读的.

Basically, the Javadoc is rather confusing because if you modify the map at all (including when you are merely changing the value associated with an existing key), you want to synchronize all operations in almost all cases. The (almost) only time you do not need to synchronize is if the map is completely read-only after being published.

现在,为什么Javadoc会说 If ...至少一个线程在结构上修改了地图-这是因为如果您仅更改与现有键相关联的值,那么最糟糕的是可能发生的事情是您在一段未指定的时间内读取了过时的值.相反,如果在没有同步的情况下进行了结构更改,则可能会发生更糟糕的事情(例如 NullPointerException s,无限循环).

Now, why does the Javadoc say If ... at least one of the threads modifies the map structurally - it's because if you are merely changing the value associated with an existing key, then the worst thing that can happen is that you read stale value for some unspecified time. In contrast, if a structural change is made without synchronization, then much worse things can happen (like NullPointerExceptions, infinite loops).

然而,同步或使用并发集合总比允许陈旧的值好得多.

It's however almost always better to synchronize or use a concurrent collection rather than allowing stale values.

这篇关于TreeMap-同步文档说明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆