ReentrantLock实现

通过ReentrantLock源码,分析下Java Lock接口的实现

ReentrantLock lock = new ReentrantLock();
Condition condition = lock.newCondition();
new Thread(() -> {
    lock.lock();
    try {
        System.out.println("start wait t1");
        condition.await();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    System.out.println("lock unlock t1");
    lock.unlock();
}).start();
new Thread(() -> {
    lock.lock();
    System.out.println("start lock t2");
    try {
        Thread.sleep(200);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    System.out.println("condition notify t2");
    condition.signal();
    System.out.println("lock unlock t2");
    lock.unlock();
}).start();

// 输出结果
/**
 * start wait t1
 * start lock t2
 * condition notify t2
 * lock unlock t2
 * lock unlock t1
 */

上面的代码主要是对ReentrantLock的使用,涉及到 lock(), unlock(), newCondition(), 前面两个方法是获取锁和释放锁,最后一个方法是创建一个新的condition对象,这个对象实现了类似 object.wait()/object.notify() 生产者消费者模型.这个之后会继续介绍.

接下来的分析分为两部分,第一部分是 ReentrantLock 的源码实现方式,第二部分是 Condition 的源码实现

ReentrantLock的源码实现

/**
 * Creates an instance of {@code ReentrantLock}.
 * This is equivalent to using {@code ReentrantLock(false)}.
 */
public ReentrantLock() {
    sync = new NonfairSync();
}

ReentrantLock 内部是通过非公平锁实现的,要理解非公平锁,就要理解 AbstractQueuedSynchronizer 查看 NonfairSync 的继承关系如下:

  • AbstractOwnableSynchronizer
    • AbstractQueuedSynchronizer
      • Sync
        • NonfairSync
AbstractOwnableSynchronizer
/**
 * The current owner of exclusive mode synchronization.
 */
private transient Thread exclusiveOwnerThread;
/**
 * Sets the thread that currently owns exclusive access.
 * A {@code null} argument indicates that no thread owns access.
 * This method does not otherwise impose any synchronization or
 * {@code volatile} field accesses.
 * @param thread the owner thread
 */
protected final void setExclusiveOwnerThread(Thread thread) {
    exclusiveOwnerThread = thread;
}
/**
 * Returns the thread last set by {@code setExclusiveOwnerThread},
 * or {@code null} if never set.  This method does not otherwise
 * impose any synchronization or {@code volatile} field accesses.
 * @return the owner thread
 */
protected final Thread getExclusiveOwnerThread() {
    return exclusiveOwnerThread;
}

AbstractOwnableSynchronizer 如果以面向对象的方式来理解的话,这个类的对象代表的是一个同步器,这个同步器只能被一个线程拥有,所以它只有一个属性 exclusiveOwnerThread ,给这个属性赋值就代表,这个线程获取了这个同步器.

这里面有个问题,就是多线程竞争的情况下,setExclusiveOwnerThread()的参数会指向那个线程,答案在它的实现类 AbstractQueuedSynchronizer 中.

AbstractQueuedSynchronizer

划重点,首先这个类是一个双向链表的数据结构,对应两个Node属性: head, tail;再有就是这个类里面有一个 volatile 修饰的 state 属性,Java Thread竞争同步器的方式是通过CAS原子指令给state赋值实现的,就是说那个Thread成功的给state赋值了,AbstractOwnableSynchronizer.exclusiveOwnerThread就指向那个Thread. 接下来就通过代码来一步步的分析它具体是如何实现的.

Step One: Lock 内部实现代码

通过Lock接口实现的同步代码,都会先调用 lock.lock() 的方法,所以以这个方法为入口,进行分析.

/**
 * Acquires the lock.
 */
public void lock() {
    sync.lock();
}

class:Sync {
    @ReservedStackAccess
    final void lock() {
        if (!initialTryLock())
            acquire(1);
    }
    
    /**
     * Checks for reentrancy and acquires if lock immediately
     * available under fair vs nonfair rules. Locking methods
     * perform initialTryLock check before relaying to
     * corresponding AQS acquire methods.
    */
    abstract boolean initialTryLock();
}
  1. Lock接口的lock()方法内部通过 Sync.lock() 实现
  2. initialTryLock()是一个抽象方法,返回一个Boolean类型的对象,如果返回true才会真正的去尝试获取锁.这个方法用于拦截获取锁的行为,可以用来解释一下什么是公平锁和非公平锁,这里先说理论:
    • 公平锁,新创建的线程在调用Sync.lock()方法时,如果是公平锁,就会先检测双向队列中是否有等待获取锁的线程,如果有则当前线程会被放在双向队列的队尾,它前面的线程都获取锁且从队列中移除之后才会尝试获取锁.
    • 非公平锁,新创建的线程会直接尝试获取锁,获取失败之后再放到队尾中.
    • 所以公平锁和非公平锁不同点就在于获取锁的行为是否被拦截
  3. acquire(1) 是通过CAS指令尝试给 state 赋值,赋值成功的则为获取同步器的线程.

Step Two: 获取锁的方式

/**
 * Acquires in exclusive mode, ignoring interrupts.  Implemented
 * by invoking at least once {@link #tryAcquire},
 * returning on success.  Otherwise the thread is queued, possibly
 * repeatedly blocking and unblocking, invoking {@link
 * #tryAcquire} until success.  This method can be used
 * to implement method {@link Lock#lock}.
 */
public final void acquire(int arg) {
    if (!tryAcquire(arg))
        acquire(null, arg, false, false, false, 0L);
}

class: NonfireSync {
    /**
     * Acquire for non-reentrant cases after initialTryLock prescreen
     */
    protected final boolean tryAcquire(int acquires) {
        if (getState() == 0 && compareAndSetState(0, acquires)) {
            setExclusiveOwnerThread(Thread.currentThread());
            return true;
        }
        return false;
    }
}

acquire()方法定义了两个行为,一个是尝试获取锁,另一个是获取失败入队列.

  1. getState() == 0代表当前没有线程获取到锁, 如果不为0说明已经有线程获取到锁了,就不需要再执行CAS操作了.
  2. 实际获取锁的方式就是CAS指令给state赋值,成功则获得锁,失败则加入队列

Step Three: 加入队列的实现代码

final int acquire(Node node, int arg, boolean shared,
                  boolean interruptible, boolean timed, long time) {
    Thread current = Thread.currentThread();
    byte spins = 0, postSpins = 0;   // retries upon unpark of first thread
    boolean interrupted = false, first = false;
    Node pred = null;                // predecessor of node when enqueued
    
    for (;;) {
        if (!first && (pred = (node == null) ? null : node.prev) != null &&
            !(first = (head == pred))) {
            if (pred.status < 0) {
                cleanQueue();           // predecessor cancelled
                continue;
            } else if (pred.prev == null) {
                Thread.onSpinWait();    // ensure serialization
                continue;
            }
        }
        if (first || pred == null) {
            boolean acquired;
            try {
                if (shared)
                    acquired = (tryAcquireShared(arg) >= 0);
                else
                    acquired = tryAcquire(arg);
            } catch (Throwable ex) {
                cancelAcquire(node, interrupted, false);
                throw ex;
            }
            if (acquired) {
                if (first) {
                    node.prev = null;
                    head = node;
                    pred.next = null;
                    node.waiter = null;
                    if (shared)
                        signalNextIfShared(node);
                    if (interrupted)
                        current.interrupt();
                }
                return 1;
            }
        }
        if (node == null) {                 // allocate; retry before enqueue
            if (shared)
                node = new SharedNode();
            else
                node = new ExclusiveNode();
        } else if (pred == null) {          // try to enqueue
            node.waiter = current;
            Node t = tail;
            node.setPrevRelaxed(t);         // avoid unnecessary fence
            if (t == null)
                tryInitializeHead();
            else if (!casTail(t, node))
                node.setPrevRelaxed(null);  // back out
            else
                t.next = node;
        } else if (first && spins != 0) {
            --spins;                        // reduce unfairness on rewaits
            Thread.onSpinWait();
        } else if (node.status == 0) {
            node.status = WAITING;          // enable signal and recheck
        } else {
            long nanos;
            spins = postSpins = (byte)((postSpins << 1) | 1);
            if (!timed)
                LockSupport.park(this);
            else if ((nanos = time - System.nanoTime()) > 0L)
                LockSupport.parkNanos(this, nanos);
            else
                break;
            node.clearStatus();
            if ((interrupted |= Thread.interrupted()) && interruptible)
                break;
        }
    }
    return cancelAcquire(node, interrupted, interruptible);
}

这段代码比较多,但是主要的功能有三个:

  • 把当前线程封装到新创建的Node中,放入队列
  • 多次循环遍历调用 tryAcquire() 尝试获取锁,可以对比synchronized自旋优化
  • LockSupport.park()休眠当前线程

现在根据acquire(1)的调用分析下具体的执行逻辑

  1. 第一次循环时 first = false, pre = null. 因为这时node = null, 所以在这个条件下会创建一个新的ExclusiveNode对象.
  2. 第二次时虽然node不为null,但是node.pre = null, 所以pred = null, 在这个条件下会创建一个新的ExclusiveNode对象,赋值给双向队列的两个对象 head = tail = newNode
  3. 第三次时会设置tail对象指向当前node,且node.pre = head
  4. 第四次时pred = head, node.status = WAITING
  5. 第五次时调用 LockSupport.park()对线程做休眠操作,直到被唤醒.

Step Four: 释放锁,唤醒队列

/**
 * Attempts to release this lock.
 *
 * <p>If the current thread is the holder of this lock then the hold
 * count is decremented.  If the hold count is now zero then the lock
 * is released.  If the current thread is not the holder of this
 * lock then {@link IllegalMonitorStateException} is thrown.
 */
public void unlock() {
    sync.release(1);
}

class: AbstractQueuedSynchronizer {
    /**
     * Releases in exclusive mode.  Implemented by unblocking one or
     * more threads if {@link #tryRelease} returns true.
     * This method can be used to implement method {@link Lock#unlock}.
     *
     * @param arg the release argument.  This value is conveyed to
     *        {@link #tryRelease} but is otherwise uninterpreted and
     *        can represent anything you like.
     * @return the value returned from {@link #tryRelease}
     */
    public final boolean release(int arg) {
        if (tryRelease(arg)) {
            signalNext(head);
            return true;
        }
        return false;
    }
}

class: Sync {
    @ReservedStackAccess
    protected final boolean tryRelease(int releases) {
        int c = getState() - releases;
        if (getExclusiveOwnerThread() != Thread.currentThread())
            throw new IllegalMonitorStateException();
        boolean free = (c == 0);
        if (free)
            setExclusiveOwnerThread(null);
        setState(c);
        return free;
    }
}
  1. Lock.unlock()方法内部调用的是AbstractQueuedSynchronizer.release()函数,这个函数主要是设置当前 state = state - arg. (可重入锁的state有可能大于1)
  2. 如果state == 0,表明没有线程持有当前Lock锁,通知队列中的线程去获取锁

Step Five: 唤醒对象头的线程

/**
 * Wakes up the successor of given node, if one exists, and unsets its
 * WAITING status to avoid park race. This may fail to wake up an
 * eligible thread when one or more have been cancelled, but
 * cancelAcquire ensures liveness.
 */
private static void signalNext(Node h) {
    Node s;
    if (h != null && (s = h.next) != null && s.status != 0) {
        s.getAndUnsetStatus(WAITING);
        LockSupport.unpark(s.waiter);
    }
}
  1. Step Three的时候知道,Node.status = WAITING,且调用了LockSupport.park()方法使得线程休眠,此时调用 LockSupport.unpark(s.waiter),则会唤醒线程
  2. 被唤醒的线程会继续执行 Step Three 中的for循环,去获取锁
  3. 获取到锁后,移除原先的head,并设置head指当前Node

到这里 ReentrantLock 的lock()和unlock()源码就都已分析完,做一个对比总结.

  1. 锁标记,如果是使用synchronized同步代码块实现锁,则需要一个object对象,然后线程获取锁后,当前对象的对象头会指向当前线程.而在ReentrantLock中,则是通过 AbstractOwnableSynchronizer.exclusiveOwnerThread 指向已获取到锁的线程来实现的.
  2. 锁竞争,synchronized 关键字编译后就是 monitorEnter 和 monitorExit两个字节码指令,而reentrantLock则是通过 cas 指令来实现
  3. 阻塞队列,synchronized 内部队列实现方式不是很清楚,但是 lock 的实现就是通过一个双向队列实现的

Condition源码实现

Condition 可用于线程间的协作,生产者消费者模型就是一个很好的例子.

Step One: 创建Condition对象

public Condition newCondition() {
    return sync.newCondition();
}

class: Sync {
    final ConditionObject newCondition() {
        return new ConditionObject();
    }
}

Condition 是一个接口,newCondition()返回一个Condition的实现类ConditionObject对象

Step Two: codition.await()

public final void await() throws InterruptedException {
    if (Thread.interrupted())
        throw new InterruptedException();
    ConditionNode node = new ConditionNode();
    int savedState = enableWait(node);
    LockSupport.setCurrentBlocker(this); // for back-compatibility
    boolean interrupted = false, cancelled = false;
    while (!canReacquire(node)) {
        if (interrupted |= Thread.interrupted()) {
            if (cancelled = (node.getAndUnsetStatus(COND) & COND) != 0)
                break;              // else interrupted after signal
        } else if ((node.status & COND) != 0) {
            try {
                ForkJoinPool.managedBlock(node);
            } catch (InterruptedException ie) {
                interrupted = true;
            }
        } else
            Thread.onSpinWait();    // awoke while enqueuing
    }
    LockSupport.setCurrentBlocker(null);
    node.clearStatus();
    acquire(node, savedState, false, false, false, 0L);
    if (interrupted) {
        if (cancelled) {
            unlinkCancelledWaiters(node);
            throw new InterruptedException();
        }
        Thread.currentThread().interrupt();
    }
}

这段代码主要做了三件事,第一件是创建一个ConditionNode对象并入队ConditionObject的双向链表的队尾,第二件是循环判断是否唤醒,未被唤醒时就一直阻塞,第三件事是被唤醒后,尝试获取锁.

入队-ConditionObject双向队列

/**
 * Adds node to condition list and releases lock.
 *
 * @param node the node
 * @return savedState to reacquire after wait
 */
private int enableWait(ConditionNode node) {
    if (isHeldExclusively()) {
        node.waiter = Thread.currentThread();
        node.setStatusRelaxed(COND | WAITING);
        ConditionNode last = lastWaiter;
        if (last == null)
            firstWaiter = node;
        else
            last.nextWaiter = node;
        lastWaiter = node;
        int savedState = getState();
        if (release(savedState))
            return savedState;
    }
    node.status = CANCELLED; // lock not held or inconsistent
    throw new IllegalMonitorStateException();
}

进入队列的代码在方法 enableWait() 中,在这个方法中会先判断当前线程是否已经获得锁,如果没获得会报 IllegalMonitorStateException 异常.之后会调用 release(savedState) 方法,释放锁,注意这个时候线程内的Runnable并没有执行完,且没有进入 Sync 队列,而是进入了 ConditionObject 队列.

循环检测是否被唤醒,否则休眠

while (!canReacquire(node)) {
    if (interrupted |= Thread.interrupted()) {
        if (cancelled = (node.getAndUnsetStatus(COND) & COND) != 0)
            break;              // else interrupted after signal
    } else if ((node.status & COND) != 0) {
        try {
            ForkJoinPool.managedBlock(node);
        } catch (InterruptedException ie) {
            interrupted = true;
        }
    } else
        Thread.onSpinWait();    // awoke while enqueuing
}

/**
 * Returns true if a node that was initially placed on a condition
 * queue is now ready to reacquire on sync queue.
 * @param node the node
 * @return true if is reacquiring
 */
private boolean canReacquire(ConditionNode node) {
    // check links, not status to avoid enqueue race
    return node != null && node.prev != null && isEnqueued(node);
}

在方法 canReacquire() 中,会判断当前Node是否在 Sync 队列中,如果在 Sync 队列中则表明已被唤醒,不然就是未唤醒状态,需要一直休眠.condition.signal()方法会唤醒线程,这个过程之后再分析,唤醒的标志是ConditionNode入队 Sync 双向队列.

唤醒后的获取锁行为

退出While循环之后,调用acquire()方法,就是尝试获取锁,且state值是之前保存的值.

Step three: 唤醒condition.signal()

这个方法会唤醒等待的线程,并调用获取锁的方法.

/**
 * Moves the longest-waiting thread, if one exists, from the
 * wait queue for this condition to the wait queue for the
 * owning lock.
 *
 * @throws IllegalMonitorStateException if {@link #isHeldExclusively}
 *         returns {@code false}
 */
public final void signal() {
    ConditionNode first = firstWaiter;
    if (!isHeldExclusively())
        throw new IllegalMonitorStateException();
    if (first != null)
        doSignal(first, false);
}

/**
 * Removes and transfers one or all waiters to sync queue.
 */
private void doSignal(ConditionNode first, boolean all) {
    while (first != null) {
        ConditionNode next = first.nextWaiter;
        if ((firstWaiter = next) == null)
            lastWaiter = null;
        if ((first.getAndUnsetStatus(COND) & COND) != 0) {
            enqueue(first);
            if (!all)
                break;
        }
        first = next;
    }
}

/**
 * Enqueues the node unless null. (Currently used only for
 * ConditionNodes; other cases are interleaved with acquires.)
 */
final void enqueue(Node node) {
    if (node != null) {
        for (;;) {
            Node t = tail;
            node.setPrevRelaxed(t);        // avoid unnecessary fence
            if (t == null)                 // initialize
                tryInitializeHead();
            else if (casTail(t, node)) {
                t.next = node;
                if (t.status < 0)          // wake up to clean link
                    LockSupport.unpark(node.waiter);
                break;
            }
        }
    }
}

上面的代码就是就是把 ConditionObject 队列的ConditionNode, 方法 Sync 队列的过程.执行完这段代码,当前线程才可以去获取锁,并且获取锁之后会继续执行之后的代码.

总结:
  1. 分析过 ReentrantLock 和 Condition 的源码之后,再看文章开头的代码,应该就能理解它内部的具体实现逻辑.
    • Thread1 先获取锁,此时Thread2也尝试调用 lock.lock() 那么就会进入 Sync 队列并休眠
    • Thread1 调用 condition.await()时会入队到 ConditionObject 队列且释放锁,然后 Thread2 获取锁,这时候没有Thraed1竞争.
    • 之后 Thread2 调用 condition.signal() 就会唤起线程 Thread1 进入 Sync 队列等待获取锁,之后 Thread2 执行完之后 Thread1 获取锁.
  2. 同步代码块 synchronized 中调用object.wait()也会进入阻塞队列,但是这部分代码是在底层实现的,ConditionObject 的实现可以辅助去理解.
  3. AQS 的使用还有很多,比如可重入锁,非可重入,互斥锁和共享锁等
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值