英文:
Why do synchronized wrappers exist for List,Set,Map when there is Collections.synchronizedCollection()
问题
有人知道为什么我应该将我的 List(例如)放在 Collections.synchronizedList()
中,而不是 Collections.synchronizedCollection()
中吗?它们的工作原理相同吗?对 Map、Set 也适用。
另外一件事情,为什么没有 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论