john
john

Reputation: 11679

simple multithreading program crashing?

I have this below program when I run it, it crashes. Looks like there is some problem at runtime. I am not able to understand what's wrong? Can anyone provide any explanation?

public static void main(String[] args) {
    final ArrayList<Object> holder = new ArrayList<>();
    final Runnable runnable = new Runnable() {
        public void run() {
            for (int i = 1; i <= 1000000; i++) {
                holder.add(new Object());
            }

        }
    };

    new Thread(runnable).start();
    new Thread(runnable).start();
    new Thread(runnable).start();
}

Here is error message but why I am getting ArrayIndexOutOfBoundsException. Can anyone provide explanation?

Exception in thread "Thread-5" java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 244

Upvotes: 1

Views: 1384

Answers (2)

MikeVe
MikeVe

Reputation: 1120

You get this error because several threads try to access the same list. For example if Thread 1 accesses List index 20 and at the same time Thread 2 accesses List index 20 it causes problems. There is a simple solution to solve this:

public static void main(String[] args) {
    final Runnable runnable = new Runnable() {
        public void run() {
        final ArrayList<Object> holder = new ArrayList<>();
            for (int i = 1; i <= 1000000; i++) {
                holder.add(new Object());
            }

        }
    };

    new Thread(runnable).start();
    new Thread(runnable).start();
    new Thread(runnable).start();
}

I simple put the List in the run()-Method so each thread has its own list. That way it should work.

Upvotes: 0

Eric J.
Eric J.

Reputation: 150108

You have multiple threads adding to an ArrayList. However, adding is not a thread-safe operation

Note that this implementation is not synchronized. If multiple threads access an ArrayList instance concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification.)

http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html

Upvotes: 4

Related Questions