为什么Java的同步集合不使用读/写锁? [英] Why do Java's synchronized Collections not use Read/Write locks?

查看:234
本文介绍了为什么Java的同步集合不使用读/写锁?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

之后,像 Hashtable 向量之后,当收集同步包装器出现时,我认为同步将更有效地处理。现在我查看了代码,我很惊讶,它真的只是包装集合与同步块。



为什么 ReadWriteLock 不包括在集合中的SynchronizedMap中?是否有一些效率考虑,不值得吗?

解决方案

读写锁是性能优化的一部分,意味着它可以在某些情况下允许更大的并发。必要条件是,它们应用于大多数时间但未修改的数据结构。



在其他条件下执行稍微比排他锁更糟糕,这是非常自然的,因为它们有更大的复杂性。



这是最有效的,如果读写锁的锁通常为一个适中的长时间,只有少量修改保护资源。



因此,读写锁是否优于互斥锁取决于用例。最终你必须用分析测量哪些锁性能更好。



考虑到这一点似乎适合选择一个排他锁 Collections.synchronizedMap 处理一般用例,而不是大多数读者的特殊情况。



其他链接 b
$ b




[...]配置,其中写操作更多的
流行,同步块的版本比
快一个基于读写锁与Sun 1.6.0_07 JVM(14%快
与Sun 1.5.0_15 JVM)。



在只有1个b $ b读卡器和1个写入器的低争用情况下,性能差异不太极端,
和三种类型的锁中的每一种在
或至少一个机器/ VM配置下产生最快的版本(例如,注意到ReentrantLocks在具有Sun 1.5.0_15 JVM的2核机器上是最快的) p>


After stuff like Hashtable and Vector where discouraged, and when the Collections synchronized wrappers came up, I thought synchronization would be handled more efficiently. Now that I looked into the code, I'm surprised that it really is just wrapping the collections with synchronization blocks.

Why are ReadWriteLocks not included into, for example, SynchronizedMap in Collections? Is there some efficiency consideration that doesn't make it worth it?

解决方案

Read-write locks are part of performance optimization, which means it can allow greater concurrency in certain situations. The necessary condition is, that they are applied on data structures which are read most of the time, but not modified.

Under other conditions they perform slightly worse than exclusive locks, which comes natural since they have a greater complexity.

It is most efficient, if the locks of a read-write lock are held typically for a moderately long time and only few modifications on the guarded resources.

Hence, whether read-write locks are better than exclusive locks depends on the use case. Eventually you have to measure with profiling which locks perform better.

Taking this into account it seems fitting to choose an exclusive lock for Collections.synchronizedMap addressing the general use case instead of the special case with mostly-readers.

Further Links

[...] However, in a configuration where write operations were more prevalent, the version with synchronized blocks was 50% faster than one based on read-write locks with the Sun 1.6.0_07 JVM (14% faster with the Sun 1.5.0_15 JVM).

In a low-contention case with just 1 reader and 1 writer, the performance differences were less extreme, and each of the three types of locks yielded the fastest version on at least one machine/VM configuration (e.g., note that ReentrantLocks were fastest on the 2-core machine with the Sun 1.5.0_15 JVM).

这篇关于为什么Java的同步集合不使用读/写锁?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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