I have a Java ArrayList, that is being used by 500+ threads simultaneously. For some reason, the synchronization block is not ensuring synchronization on a Java Array List. I known that ArrayLists are non thread-safe, i.e., they are not synchronized. However, I thought that by wrapping the list into a synchronized block I would achieve that. Unfortunately, in rare (but in some situations) two or more threads are entering the synchronized block simultaneously, which is giving me non-deterministic behaviour. Am I missing something? How can I guarantee that my array list (or any other list collection) are completely thread safe throughout 500+ simultaneous threads operating in the array.
There is a related question, (Correct way to synchronize ArrayList in java), but I did not understood its answer. Should I create a Synchronized collection at every "run" of my threads???
Sample:
Thread 1
synchronized (_myList) {
Iterator it = _myList.iterator();
...
}
Thread 2
synchronized (_myList) {
Iterator it = _myList.iterator();
...
}
Thread n
synchronized (_myList) {
Iterator it = _myList.iterator();
...
}
_myListbut then iterating over_unackedSentQueue... why? If two instances have different_myListreferences but the same_unackedSentQueuereferences, that will cause the problem you're seeing. Ideally, you should post a short but complete program demonstrating the problem. Fundamentally you should probably consider using a list implementation designed for this though...Vectorif you need a synchronized variant of arraylist.Object _unackedSentQueueLock = new Object()then use that for your synchronized locks. Alternatively you could always just synchronize with the list your actually using_unackedSentQueue_myList.wait();?