I\'ve been at this for a week now doing my research on how to properly synchronize an ArrayList.
My main issue in a nutshell is I have a \"master\" ArrayList of objects.
Use CopyOnWriteArrayList, and synchronize on write operations only
CopyOnWriteArrayList list = ...
final Object writeLock = new Object();
void writeOpA()
{
synchronized(writeLock)
{
read/write list
}
}
void writeOpB()
{
synchronized(writeLock)
{
read/write list
}
}
Therefore no two write sessions will overlap with each other.
Reads require no lock. But a read session may see a changing list. If we want a read session to see a snapshot of the list, either use iterator()
, or take a snapshot by toArray()
.
It's probably even better if you do the copy-on-write yourselves
volatile Foo data = new Foo(); // ArrayList in your case
final Object writeLock = new Object();
void writeOpA()
{
synchronized(writeLock)
{
Foo clone = data.clone();
// read/write clone
data = clone;
}
}
void writeOpB()
{
// similar...
}
void readSession()
{
Foo snapshot = data;
// read snapshot
}