0

I have a loop like:

synchronized(list) {
    int objectsN = list.size();
    for (int i=0; i < objectsN; i++) {
        // Do stuff...
    }
}

list is a final field of an object in which this code is.

And then I have a method in the same object which calls list.remove(index) and it is called by the other thread while some thread is executing above code listing in an infinite loop (with sleep between single cycles) and SOMETIMES it crashes giving IndexOutOfBoundsException.

How to synchronize this list properly?

4
  • 1
    You should take a look at: docs.oracle.com/javase/7/docs/api/java/util/Vector.html
    – huidube
    Apr 23, 2015 at 15:31
  • Can you show the code for the other thread. Also, multi-threaded or not, remove will always throw that exception if you pass a non-existent index. Apr 23, 2015 at 15:31
  • @huidube Why is this class better than ArrayList? Apr 23, 2015 at 15:33
  • 1
    Well, vector is build-in synchronized. But you better take a look on Reimeus answer. Its even a better choice.
    – huidube
    Apr 23, 2015 at 15:35

2 Answers 2

4

Synchronizing the remove statement would solve the concurrency.

synchronized (list) {
    list.remove(index);
}

If you use Java 8 you could use a Collections.synchronizedList(list) when you define your list and call list.foreach(currentElement -> {// Do stuff...})

private List<?> list;

public Constructor(list) {
    this.list = Collections.synchronizedList(list);
}

public void loopingMethod() {
    list.foreach(currentElement -> {// Do stuff...});
}

public void deletingMethod(int index) {
    list.remove(index); // This assumes the index is within bound
}
1
  • Thank you. Using synchronizedList and leaving synchronized block solved the problem. Apr 23, 2015 at 19:58
0

The idea is to take a lock on a common object if two methods intend to change the same data. One doesn't even have to synchronize on the list object here, any object would do, but both the looping and deleting methods should use it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.