If I have a data structure in a multithreaded application that I want to access simultaneously with reads while it's not altered, but disallow both read and write access to other threads while one is writing?
For simplicity, let's say I have an array and two methods read()
and write()
:
int[] rgData;
// ...
int read(int ix) {
return rgData[ix];
}
void write(int ix, int val) {
rgData[ix] = val;
}
In reality, the data structure and the two access methods are more complex. Now, if I use Java's object monitors and wrap the calls to read()
and write()
like this
synchronized (rgData) {
int val = read(ix);
}
I don't have simultaneous reads anymore, which is sad, because simultaneous reading is no problem and writes are rare.
One solution could be to do all read and write jobs through a common manager that maintains a queue and a thread pool. Read jobs are run concurrently, if a write jobs comes in, it waits for all running jobs to complete, and the queue is not processed while the write job runs. But is there anything simpler?