Java -- Read/Write Locks

The "java.util.concurrent.locks" package defines two lock classes, the "ReentrantLock" and the "ReentrantReadWriteLock". The latter is useful when there are many threads that read from a data structure and fewer threads that modify it. In that situation, it makes sense to allow shared access for the all readers. Of cause, a writer must still have exclusive access.

Here are the steps that are neccessary to use a read/write lock:

1. Construct a "ReentrantReadWriteLock" object:

private ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();

2. Extract the read and write locks:

private Lock readLock = rwl.readLock();
private Lock writeLock = rwl.writeLock();

3. Use the read lock in all accessors:

public double getTotalBalance() {
    readLock.lock();
   
    try {
        ... ...
    finally {
        readLock.unlock();
    }
}

4. Use the write lock in all mutators:

public void transfer(int from, int to, double amount) {
    writeLock.lock();
   
    try {
        ... ...
    finally {
        writeLock.unlock();
    }
}

猜你喜欢

转载自blog.csdn.net/liangking81/article/details/80720120