Why do synchronized wrappers exist for List,Set,Map when there is Collections.synchronizedCollection()

huangapple go评论78阅读模式
英文:

Why do synchronized wrappers exist for List,Set,Map when there is Collections.synchronizedCollection()

问题

有人知道为什么我应该将我的 List(例如)放在 Collections.synchronizedList() 中,而不是 Collections.synchronizedCollection() 中吗?它们的工作原理相同吗?对 MapSet 也适用。

另外一件事情,为什么没有 Collections.synchronizedQueue() 呢?

英文:

Does anyone know why should I (for example) put my List inside Collections.syncrhonizedList() instead of Collections.synchronizedCollection()? Do they work the same? Same applies to Map,Set.

Another thing. Why there isn't Collections.synchronizedQueue()?

答案1

得分: 2

当您使用synchronizedCollection()来同步一个ArrayList时,列表特定的方法并没有被同步,所以具体的方法越好。请注意,Collections.synchronizedList()方法会同步对支持的列表的所有访问,除了在迭代时,仍然需要在一个带有同步块的情况下进行,其中对象的监视器是同步的列表实例。还有一点,当您使用Collections.synchronizedCollection来创建同步的集合,如下所示:

Collection c = Collections.synchronizedCollection(yourCollection);

然后,根据文档,返回的集合不会将hashCode和equals操作传递给支持的集合,而是依赖于Object的equals和hashCode方法。这对于保留这些操作的契约是必要的,特别是在支持的集合是集合或列表的情况下。

英文:

When you are using synchronizedCollection() to synchronize an ArrayList, the list-specific methods are not synchronized, so the more concrete method, the better. Beware that method Collections.synchronizedList() will synchronize all the accesses to the backed list except while iterating which still needs to be done within a synchronized block with the synchronized List instance as object's monitor. One more thing, when you create synchronized collection using Collections.synchronizedCollection like this :

Collection c = Collections.synchronizedCollection(yourCollection);

Then, according to documentation, the returned collection does not pass the hashCode and equals operations through to the backing collection, but relies on Object's equals and hashCode methods. This is necessary to preserve the contracts of these operations in the case that the backing collection is a set or a list.

huangapple
  • 本文由 发表于 2020年8月24日 19:42:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/63560347.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定