I was reading about CopyOnWriteArrayList and was wondering how can I demonstrate data race in ArrayList class. Basically I’m trying to simulate a situation where ArrayList fails so that it becomes necessary to use CopyOnWriteArrayList. Any suggestions on how to simulate this.
I was reading about CopyOnWriteArrayList and was wondering how can I demonstrate data race
Share
A race is when two (or more) threads try to operate on shared data, and the final output depends on the order the data is accessed (and that order is indeterministic)
From Wikipedia:
For example:
This, however, fails when using
ArrayList, withArrayIndexOutOfbounds. That’s because before insertion theensureCapacity(..)should be called to make sure the internal array can hold the new data. And here’s what happens:add(..), which in turn callsensureCapacity(currentSize + 1)ensureCapacity(currentSize + 1).currentSize, the new size of the internal array iscurrentSize + 1array[size++]. The first one succeeds, the second one fails, because the internal array has not been expanded properly, due to the rece condition.This happens, because two threads have tried to add items at the same time on the same structure, and the addition of one of them has overridden the addition of the other (i.e. the first one was lost)
Another benefit of
CopyOnWriteArrayListArrayListArrayList. It will surely getConcurrentModificationExceptionHere’s how to demonstrate it:
If you run this program multiple times, you will often be getting
ConcurrentModificationExceptionbefore you getOutOfMemoryError.If you replace it with
CopyOnWriteArrayList, you don’t get the exception (but the program is very slow)Note that this is just a demonstration – the benefit of
CopyOnWriteArrayListis when the number of reads vastly outnumbers the number of writes.