如何证明arraylist对测试不是线程安全的?

Nep*_*daj 5 java arraylist thread-safety

在我们的应用程序中,我们在ArrayList.add(Object o)操作上得到了一个ArrayIndexOutOfBounds异常.最明显的解释是线程安全,但我无法重新创建事件.我试过创建两个线程.在一个我添加元素,在另一个我正在删除它们(或清除数组),但我没有第二次得到异常.我的意思是很明显它可以通过查看ArrayList的源代码来实现,但是能够演示它会很好.

我已经运行了这个测试很长一段时间,没有任何例外:

public class Test {
static ArrayList a = new ArrayList();

public static void main(String[] args) throws Exception {
    Thread t1 = new Thread() {
        public void run() {
            while (true) {
                if (a.size() > 0)
                    a.remove(0);
            }
        }
    };

    Thread t2 = new Thread() {
        public void run() {
            while (true) {
                a.add(new Object());
            }
        }
    };

    t2.start();
    Thread.sleep(100);
    t1.start();
}
}
Run Code Online (Sandbox Code Playgroud)

Nep*_*daj 6

感谢isnot2bad的评论,我在我的假设中发现了一个问题.问题在于并发添加,而不是添加/删除.我能够创建一个失败的测试:

static ArrayList a = new ArrayList(1);

public static void main(String[] args) throws Exception {
    Thread t1 = new Thread() {
        public void run() {
            while (true) {
                a.add(new Object());
            }
        }
    };

    Thread t2 = new Thread() {
        public void run() {
            while (true) {
                a = new ArrayList(1);
                a.add(new Object());
                a.add(new Object());
            }
        }
    };

    t2.start();
    Thread.sleep(100);
    t1.start();
}
Run Code Online (Sandbox Code Playgroud)

在第一个线程的添加行,我得到这个:

Exception in thread "Thread-0" java.lang.ArrayIndexOutOfBoundsException: 2 
Run Code Online (Sandbox Code Playgroud)

:)