I have these classes that I use to create objects that I want to store at runtime
Class Person
String name
Pet[] pets
Class Pet
String name
Person[] owners
boolean neutered
At first I used these HashMaps to store them
HashMap people
HashMap pets
But I wanted to make the implementation concurrent so I changed these maps like so
ConcurrentHashMap people
ConcurrentHashMap pets
I used the "compareAndSet in a while loop" pattern
to make atomic updates.
But I still had a problem because each person in my People
map has associated pets in the Pets
map. To keep updates atomic I added ReentrantReadWriteLocks
So that I could update People
objects simultaneously with associated Pet
objects.
ConcurrentHashMap people
ConcurrentHashMap peopleLocks
ConcurrentHashMap pets
ConcurrentHashMap petLocks
Now when I perform an edit on multiple records, I first grab all the write locks, then I make my edits, and finally release the write locks. This ensures no reading while I make the update.
changePetNames(Person person, Pets[] pets, String[] names) {
// get Person lock
// get Pet locks
// make updates
// release locks
}
neuter(Pets[] pets) {
// get Pet locks
// make updates
// release locks
I then had all my edit methods synchronize on one object, so that competing edits wouldn't deadlock
private final Object leash = new Object();
changePetNames(Person person, Pets[] pets, String[] names) {
synchronized(leash) {
// get Person lock
// get Pet locks
// make updates
// release locks
}
}
neuter(Pets[] pets) {
synchronized(leash) {
// get Pet locks
// make updates
// release locks
}
}
So now I have runtime storage that allows concurrent reads and synchronized writes. My question is whether there's a way to make the writes concurrent as well while protecting the relationship between people and pets.