java并发编程的艺术-ReentrantLock公平锁原理分析

4 篇文章 0 订阅
1 篇文章 0 订阅

lock方法分析

	final void lock() {
        acquire(1);
    }

该lock方法会调用AbstractQueuedSynchronizer的acquire方法

	/**
     * 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}.
     *
     * @param arg the acquire argument.  This value is conveyed to
     *        {@link #tryAcquire} but is otherwise uninterpreted and
     *        can represent anything you like.
     */
	public final void acquire(int arg) {
        if (!tryAcquire(arg) &&
            acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
            selfInterrupt();
    }

acquire方法首先调用了tryAcquire方法,公平锁实现类FairSync,方法如下:

	/**
         * Fair version of tryAcquire.  Don't grant access unless
         * recursive call or no waiters or is first.
         */
        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;
        }

该方法首先获取当前线程对象,判断所对象state值,获得锁成功的情况:

  1. 为0,没有线程成功获得锁。判断是否有线程正在获得锁(同步队列前面中有其他获取锁的线程Node),若没有,利用CAS机制设置的state值为1,如果设置为1成功,获得锁成功,设置获得锁的线程是当前线程。
  2. 不为零,有线程获得锁。判断获得锁的线程是当前线程,获得锁成功,锁state值加1,如果state的小于零,说明获取锁的次数太多导致数值移出,抛出异常。如果不是当前线程获得锁失败。
    回到AbstractQueuedSynchronizer的acquire方法,如果获取锁失败,会调用addWaiter方法构建Node对象,再调用acquireQueued方法
	/**
     * Acquires in exclusive uninterruptible mode for thread already in
     * queue. Used by condition wait methods as well as acquire.
     *
     * @param node the node
     * @param arg the acquire argument
     * @return {@code true} if interrupted while waiting
     */
    final boolean acquireQueued(final Node node, int arg) {
        boolean failed = true;
        try {
            boolean interrupted = false;
            for (;;) {
                final Node p = node.predecessor();
                if (p == head && tryAcquire(arg)) {
                    setHead(node);
                    p.next = null; // help GC
                    failed = false;
                    return interrupted;
                }
                if (shouldParkAfterFailedAcquire(p, node) &&
                    parkAndCheckInterrupt())
                    interrupted = true;
            }
        } finally {
            if (failed)
                cancelAcquire(node);
        }
    }

addWaiter方法主要把新增的Node放到队列的末尾,不做介绍,acquireQueued方法在死循环中获取锁,判断当前Node的前一个Node是否为head(第一个Node),如果是调用tryAcquire继续获得锁。获取锁成功设置当前node为head并返回false。调用shouldParkAfterFailedAcquire方法

	/**
     * Checks and updates status for a node that failed to acquire.
     * Returns true if thread should block. This is the main signal
     * control in all acquire loops.  Requires that pred == node.prev.
     *
     * @param pred node's predecessor holding status
     * @param node the node
     * @return {@code true} if thread should block
     */
    private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
        int ws = pred.waitStatus;
        if (ws == Node.SIGNAL)
            /*
             * This node has already set status asking a release
             * to signal it, so it can safely park.
             */
            return true;
        if (ws > 0) {
            /*
             * Predecessor was cancelled. Skip over predecessors and
             * indicate retry.
             */
            do {
                node.prev = pred = pred.prev;
            } while (pred.waitStatus > 0);
            pred.next = node;
        } else {
            /*
             * waitStatus must be 0 or PROPAGATE.  Indicate that we
             * need a signal, but don't park yet.  Caller will need to
             * retry to make sure it cannot acquire before parking.
             */
            compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
        }
        return false;
    }

检查前一个node的waitStatus 状态

  1. waitStatus ==Node.SIGNAL(值为-1,处于等待状态,如果该节点释放同步锁会唤醒后继节点)。 返回true,线程可以park 。
  2. waitStatus > 0 说明前一个节点已经取消,需要越过这些节点。返回false,线程不可以park。
  3. 其他值,使用CAS机制更新前一个节点的waitStatus为Node.SIGNAL。返回false,线程不可以park。
    如果线程可以park将调用parkAndCheckInterrupt使线程阻塞
	/**
     * Convenience method to park and then check if interrupted
     *
     * @return {@code true} if interrupted
     */
    private final boolean parkAndCheckInterrupt() {
        LockSupport.park(this);
        return Thread.interrupted();
    }

如果不可以park,线程将会继环执行acquireQueued方法中的死续循直到获得锁或者进入阻塞状态或者异常设置waitStatus 为1(取消状态)。

unlock方法分析

 /**
     * 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.
     *
     * @throws IllegalMonitorStateException if the current thread does not
     *         hold this lock
     */
    public void unlock() {
        sync.release(1);
    }

unlock方法会调用AbstractQueuedSynchronizer的release方法

  /**
     * 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)) {
            Node h = head;
            if (h != null && h.waitStatus != 0)
                unparkSuccessor(h);
            return true;
        }
        return false;
    }

首先调用ReentrantLock.tryRelease方法

	protected final boolean tryRelease(int releases) {
            int c = getState() - releases;
            if (Thread.currentThread() != getExclusiveOwnerThread())
                throw new IllegalMonitorStateException();
            boolean free = false;
            if (c == 0) {
                free = true;
                setExclusiveOwnerThread(null);
            }
            setState(c);
            return free;
        }
1. 如果获得锁的线程不是当前线程将抛出异常
2. 锁的state状态减1,若为0说明获得锁的次数等于释放锁的次数相等,锁释放成功,设置锁的当前执行线程为null。若大于0说明锁的释放次数小于加锁次数,还需要继续释放锁,释放锁失败。设置state的值。

回到AbstractQueuedSynchronizer的release方法。如果释放锁失败,线程还占有锁,需要继续释放锁才可能让其它线程获得锁成功。如果释放锁成功,如果锁的head(头Node不为空)并且没有被取消,调用unparkSuccessor方法

 /**
     * Wakes up node's successor, if one exists.
     *
     * @param node the node
     */
    private void unparkSuccessor(Node node) {
        /*
         * If status is negative (i.e., possibly needing signal) try
         * to clear in anticipation of signalling.  It is OK if this
         * fails or if status is changed by waiting thread.
         */
        int ws = node.waitStatus;
        if (ws < 0)
            compareAndSetWaitStatus(node, ws, 0);

        /*
         * Thread to unpark is held in successor, which is normally
         * just the next node.  But if cancelled or apparently null,
         * traverse backwards from tail to find the actual
         * non-cancelled successor.
         */
        Node s = node.next;
        if (s == null || s.waitStatus > 0) {
            s = null;
            for (Node t = tail; t != null && t != node; t = t.prev)
                if (t.waitStatus <= 0)
                    s = t;
        }
        if (s != null)
            LockSupport.unpark(s.thread);
    }

如果头结点的waitStatus<0,使用CAS机制设置头结点的waitStatus为0。
如果头结点的下一个节点为null,或为取消状态,则从尾部向前遍历找到最前面的没有取消的线程唤醒,否则唤醒下一个节点。唤醒节点的线程获得锁(继续执行AbstractQueuedSynchronizer的acquireQueued方法中的死续循)

同步队列示意图

在这里插入图片描述

AQS锁流程

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值