Exclusive write Concurrent read access

suggest change

It is sometimes required for threads to write and read the same data.

The ReadWriteLock interface and its ReentrantReadWriteLock implementation allow an access pattern that can be described as follows:

  1. There can be any number of concurrent readers of the data. If at least one reader holds the lock, no writer can acquire it.
  2. There can be at most one writer. If a writer holds the lock, no reader can acquire it.

An implementation could look like :

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class Sample {

// Our lock. The constructor allows a "fairness" setting, which guarantees the chronology of lock attributions.
protected static final ReadWriteLock RW_LOCK = new ReentrantReadWriteLock();

// This is a typical data that needs to be protected for concurrent access
protected static int data = 0;

/** This will write to the data, in an exclusive access */
public static void writeToData() {
    RW_LOCK.writeLock().lock();
    try {
        data++;
    } finally {
        RW_LOCK.writeLock().unlock();
    }
}

public static int readData() {
    RW_LOCK.readLock().lock();
    try {
        return data;
    } finally {
        RW_LOCK.readLock().unlock();
    }
}

}

NOTE 1: This particular int has a simpler solution, AtomicInteger. The pattern still applies when the data is not a single atomic value.

NOTE 2: The read lock is required. Without it:

  1. A non-volatile long or double write is not atomic, so a reader can see a torn value. A plain int write is atomic, but that is not the only issue.
  2. A write is visible to another thread only if a happens-before relationship exists. Using both the read lock and the write lock establishes that relationship.

When higher performance is required, and for some use patterns, StampedLock (Java 8) also offers an optimistic read mode. It does not work like ReadWriteLock, and this sample does not transfer to it.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents