java - CopyOnWriteArraySet 太慢

标签 java

当我运行以下程序时,执行大约需要 7 到 8 分钟。我真的不确定我哪里弄错了,因为这个程序执行起来要花很多时间。

public class Test {
            public static void main(String[] args) {
            final Integer[] a= new Integer[1000000];
            for (int i=0; i < a.length; i++) {
                a[i] = i;
            }
            final List<Integer> source = Arrays.asList(a);
            final Set<Integer> set = new CopyOnWriteArraySet<Integer>(source);
        }
    }

谁能帮我理解,为什么这个程序太慢了。

我的机器是 Core I7 和 4GB 内存

最佳答案

我已经测试过,确实有一个包含 1 000 000 个元素的列表提供给构造函数,这需要很长时间(7 分钟)。

这是 Open JDK 2013-01-09 上的一个引用问题:
JDK-8005953 - CopyOnWriteArraySet copy constructor is unusable for large collections

此问题是由 CopyOnWriteArraySet 构造函数调用的 CopyOnWriteArrayList#addAllAbsent() 方法引起的。

问题摘录:

CopyOnWriteArraySet's copy constructor is too slow for large collections. It takes over 10 minutes on a developer laptop with just 1 million entries in the collection to be copied...

作为解决状态,您可以阅读:Won't Fix
您可以阅读最后一条消息:

addAllAbsent can be made faster for larger input, but it would impact the performance for small sizes. And it's documented that CopyOnWriteXXX classes are better suited for collections of small sizes.

CopyOnWriteArraySet javadoc确实指定了这一点:

It is best suited for applications in which set sizes generally stay small, read-only operations vastly outnumber mutative operations, and you need to prevent interference among threads during traversal.

关于java - CopyOnWriteArraySet 太慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44345481/

相关文章:

java - 在运行时进行 Spring 上下文分析的最先进工具是什么?

java - 我什么时候应该覆盖 java.lang.Object 方法?

java - 不可预测的文件写入器

来自 xerial 的 Sample.java 程序中的 java.lang.ClassNotFoundException : org. sqlite.JDBC 错误

java - 将 JRebel 用于非 webapp 项目

java - 使用 snakeyaml(导入 junit 库)将 .yml 文件加载到 HashMap 中

java - 断言 double 组精确相等

java - 在java中输入数字集 - 空指针异常

java - Android - 显示来自 MySQL 的数据

java - 导入java类文本编辑器