java - 关于阻塞同步集合

标签 java collections concurrency

直接来自这个APICollections.synchronizedCollection(Collection):

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.

这是否意味着如果我有重写的方法 equalshashCode,这些重写的方法将不会被考虑在内?如果是,为什么?这是相当误导...

最佳答案

假设 equals() 只是委托(delegate)给后备集合,并假设这个后备集合是 ArrayList list

然后你会有

Collections.synchronizedCollection(list).equals(list) == true

因为它将通过委托(delegate)给 list.equals(list) 来实现。

但是你会有

list.equals(Collections.synchronizedCollection(list)) == false

因为列表不能等于不是列表的集合,并且 Collections.synchronizedCollection(list) 不是列表。

这会严重破坏 Object.equals() 的约定。如果要保持相等性,请使用 Collections.synchronizedList() 同步 List,并使用 Collections.synchronizedSet() 同步 Set。

关于java - 关于阻塞同步集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17741898/

相关文章:

Java 避免在不相交集合的情况下锁定

java - Vaadin 在表格中添加网格

java - 跟踪执行线程

java - 无法在Liferay 7中部署Portlet

java - 如何从 Java 中的集合中弹出项目?

java - Java 中 HashSet.contains() 的时间复杂度性能是多少?

java - 为什么 Java 的 AbstractList 的 removeRange() 方法受到保护?

java - Java中的并发(FX)

java - 数字排序程序无法找到符号编译错误

java - 添加 .jar 时无法运行 java