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();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值