views:

117

answers:

2

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?

+4  A: 

You want to use the ReadWriteLock, introduced in Java 1.5 which handles exactly this situation.

Andrzej Doyle
This was an answer race condition. Upvoted yours and accepted chilitom's
Hanno Fietz
+3  A: 

Use a ReadWriteLock. It does exactly what you need.

chillitom
This was an answer race condition. Accepted yours and upvoted dtsazza's
Hanno Fietz