How to allow parallel reads but block all access while writing to an object in Java?

If I have a data structure in a multithreaded application that I want to access reads concurrently until it is modified, but disallow both reads and writes to other threads while 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 accessors are more complex. Now if I use Java object monitors and post calls to read()

and write()

like this

synchronized (rgData) {
    int val = read(ix);
}

      

I no longer have concurrent reads, which is unfortunate because concurrent reads are not a problem and writes are rare.

One solution might be to perform all read and write operations through a common manager that maintains a queue and thread pool. Read jobs are done concurrently, if a write job comes in, it waits for all running jobs to complete, and the queue is not processed while the write job is running. But is there anything simpler?

+2


source to share


2 answers


Use ReadWriteLock . It does exactly what you need it to do.



+3


source


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



+4


source







All Articles