深入浅出java并发编程(ReentrantLock)

文章详细介绍了Java中的ReentrantLock,包括其构造、加锁解锁方法、公平锁与非公平锁的区别,以及如何响应中断和避免死锁。ReentrantLock提供了比synchronized更细粒度的控制,如tryLock和Condition,同时在异常处理中需确保正确释放锁。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

快速上手

    private final ReentrantLock lock = new ReentrantLock();
    // ...

    public void m() {
        lock.lock();
        try {
            //
        } finally {
            lock.unlock();
        }
    }

来自源码注释中的官方示例。

源码

package java.util.concurrent.locks;

public class ReentrantLock implements Lock, java.io.Serializable {}

Lock接口

    void lock();
    void lockInterruptibly() throws InterruptedException;
    Condition newCondition();
    boolean tryLock();
    boolean tryLock(long time, TimeUnit unit) throws InterruptedException;
    void unlock();            

加锁:lock、lockInterruptibly、tryLock、tryLock。
解锁:unlock
拿到Condition:Condition
有两个方法可以响应中断信号(带有 throws InterruptedException的方法)lockInterruptibly 和 tryLock。

ReentrantLock中的实现

    public void lock() {
        sync.lock();
    }
    public void lockInterruptibly() throws InterruptedException {
        sync.acquireInterruptibly(1);
    }
    public Condition newCondition() {
        return sync.newCondition();
    }
    public boolean tryLock() {
        return sync.nonfairTryAcquire(1);
    }
    public boolean tryLock(long timeout, TimeUnit unit)
            throws InterruptedException {
        return sync.tryAcquireNanos(1, unit.toNanos(timeout));
    }
    public void unlock() {
        sync.release(1);
    }

从这里可以看到,所有锁的实现都是基于AQS这个类,这里不做过多赘述。

public 方法

构造函数

    public ReentrantLock() {
        sync = new NonfairSync();
    }
    
    public ReentrantLock(boolean fair) {
        sync = fair ? new FairSync() : new NonfairSync();
    }

fair – true if this lock should use a fair ordering policy ,公平锁也就是排队锁。
构造函数在这个最重要的用处就是给sync赋值。

private final Sync sync;

abstract static class Sync extends AbstractQueuedSynchronizer {} 

getHoldCount

    public int getHoldCount() {
        return sync.getHoldCount();
    }

the number of holds on this lock by the current thread, or zero if this lock is not held by the current thread

当前线程持有锁的次数,如果当前线程没有持有锁则返回0。

getQueueLength

    public final int getQueueLength() {
        return sync.getQueueLength();
    }

the estimated number of threads waiting for this lock.

返回有多少线程在等待锁。

getWaitQueueLength

    public int getWaitQueueLength(Condition condition) {
        if (condition == null) {
            throw new NullPointerException();
        }
        if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject)) {
            throw new IllegalArgumentException("not owner");
        }
        return sync.getWaitQueueLength((AbstractQueuedSynchronizer.ConditionObject) condition);
    }

返回在指定Condition上等待的线程数量。

hasQueuedThread

    public final boolean hasQueuedThread(Thread thread) {
        return sync.isQueued(thread);
    }

true if the given thread is queued waiting for this lock ,如果给定的线程在队列等锁则返回true。

hasQueuedThreads

    public final boolean hasQueuedThreads() {
        return sync.hasQueuedThreads();
    }
    
    public final boolean hasQueuedThreads() {
        return head != tail;
    }

true if there maybe other threads waiting to acquire the lock,如果可能有其他线程正在等待获取锁,返回true。

底层判断队列的头和尾是否相等,如果不相等代表有其他线程在排队。

hasWaiters

    public final boolean hasWaiters(ConditionObject condition) {
        if (!owns(condition))
            throw new IllegalArgumentException("Not owner");
        return condition.hasWaiters();
    }

true if there are any waiting threads,如果有任何等待线程,则为true

isFair

    public final boolean isFair() {
        return sync instanceof FairSync;
    }

判断是否是公平锁

isHeldByCurrentThread

    public boolean isHeldByCurrentThread() {
        return sync.isHeldExclusively();
    }

true if current thread holds this lock and false otherwise,如果当前线程持有该锁,则为true,否则为false

isLocked

    public boolean isLocked() {
        return sync.isLocked();
    }

true if any thread holds this lock and false otherwise,如果任何线程持有此锁,则为true,否则为false

synchronized 对比

  1. 一个是内置关键字,一个是并发包工具类。
  2. sync不响应中断,ReentrantLock部分方法响应中断。
  3. sync会一直阻塞,ReentrantLock带有time参数的可以提前放弃。
  4. 加锁语法,ReentrantLock需要搭配异常捕获机制保证锁一定会被释放。

加锁到底是在try外还是里面?

        lock.lock();
		//1
        try {
            //2
        } finally {
            lock.unlock();
        }
        try {
        	//3
            lock.lock();
            //4
        } finally {
            lock.unlock();
        }

我的思考:

  • 方式1在1处如果有其他错误的代码会导致加锁后未释放,死锁。
  • 方式2在3处如果有其他错误的代码会导致不进行解锁,死锁。
  • 如果使用方式1,lock需要紧贴try代码块。
  • 如果使用方式2,try后紧跟try代码块。
  • 官方推荐方式1。

ReentrantLock 对比 sync 有以下几个特点 ,ReentrantLock 的解锁需要放到 finally 中,避免程序异常导致锁无法释放。

三个重要的内部类

Sync

abstract static class Sync extends AbstractQueuedSynchronizer {}

Uses AQS state to represent the number of holds on the lock. 使用AQS状态来表示持有锁的次数。

FairSync

    static final class FairSync extends Sync {
    
        final void lock() {
            acquire(1);
        }
        
        protected final boolean tryAcquire(int acquires) {
            final Thread current = Thread.currentThread();
            int c = getState();
            if (c == 0) {
                if (!hasQueuedPredecessors() &&
                    compareAndSetState(0, acquires)) {
                    setExclusiveOwnerThread(current);
                    return true;
                }
            }
            else if (current == getExclusiveOwnerThread()) {
                int nextc = c + acquires;
                if (nextc < 0)
                    throw new Error("Maximum lock count exceeded");
                setState(nextc);
                return true;
            }
            return false;
        }
    }

NonfairSync

    static final class NonfairSync extends Sync {      
            
        final void lock() {
            if (compareAndSetState(0, 1))
                setExclusiveOwnerThread(Thread.currentThread());
            else
                acquire(1);
        }

        protected final boolean tryAcquire(int acquires) {
            return nonfairTryAcquire(acquires);
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值