Lock锁的原理

Lock锁是JDK实现的,在JDK1.5开始存在。这点与Synchronized不同,Synchronized是关键字,是由JVM实现的。

以ReentrantLock锁为例:

private Lock lock=new ReentrantLock();

首先创建一个lock对象,Lock是一个接口,ReentrantLock是其一个实现类。

Lock接口中的方法有:

public interface Lock {

    //获取锁
    void lock();
    //获取锁,如果锁可用则线程继续执行;如果锁不可用则线程进入阻塞状态,此时可以在其它线程执行时        
    //调用这个线程的interrupt()方法打断它的阻塞状态。
    void lockInterruptibly() throws InterruptedException;
    //尝试非阻塞的获取锁,调用该方法后立刻返回,若能获取则返回true,反之亦然
    boolean tryLock();
    //阻塞尝试锁。参数代表时长,在指定时长内尝试锁。
    boolean tryLock(long time, TimeUnit unit) throws InterruptedException;
    //释放锁
    void unlock();
    //返回绑定到此 Lock 实例的新 Condition 实例  
    Condition newCondition();
}

看一下实现类的构造方法:

    public ReentrantLock() {
        sync = new NonfairSync();
    }

这个NonfairSync类是非公平锁实现类,所以ReentrantLock默认是非公平锁的,公平锁如何实现?

    private Lock lock=new ReentrantLock(true);

传一个Boolean类型的参数true即开启了公平锁模式

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

这里的类FairSync就是公平锁实现类。

非公平锁的类如下:

    static final class NonfairSync extends Sync {
        private static final long serialVersionUID = 7316153563782823691L;

        /**
         * Performs lock.  Try immediate barge, backing up to normal
         * acquire on failure.
         */
        final void lock() {
            if (compareAndSetState(0, 1))
                setExclusiveOwnerThread(Thread.currentThread());
            else
                acquire(1);
        }

        protected final boolean tryAcquire(int acquires) {
            return nonfairTryAcquire(acquires);
        }
    }

其中compareAndSetState方法作用:

    protected final boolean compareAndSetState(int expect, int update) {
        // See below for intrinsics setup to support this
        return unsafe.compareAndSwapInt(this, stateOffset, expect, update);
    }

读取传入对象在内存中偏移量为offset位置的值与期望值expect作比较。相等就把update值赋值给offset位置的值。方法返回true。不相等,就取消赋值,方法返回false。这也是CAS的思想,及比较并交换。用于保证并发时的无锁并发的安全性。

    protected final void setExclusiveOwnerThread(Thread thread) {
        exclusiveOwnerThread = thread;
    }

如果为true,即当前对象没有被任何线程持有,则将当前线程所有者设置为当前线程。

否则调用acquire方法:

    public final void acquire(int arg) {
        if (!tryAcquire(arg) &&
            acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
            selfInterrupt();
    }
        protected final boolean tryAcquire(int acquires) {
            return nonfairTryAcquire(acquires);
        }
        final boolean nonfairTryAcquire(int acquires) {
            final Thread current = Thread.currentThread();
            int c = getState();
            if (c == 0) {
                if (compareAndSetState(0, acquires)) {
                    setExclusiveOwnerThread(current);
                    return true;
                }
            }
            else if (current == getExclusiveOwnerThread()) {
                int nextc = c + acquires;
                if (nextc < 0) // overflow
                    throw new Error("Maximum lock count exceeded");
                setState(nextc);
                return true;
            }
            return false;
        }

首先获取当前的state:

    private volatile int state;

它是由volatile修饰的变量,一但修改对其他线程立即可见。

如果锁已被占用,tryAcquire(arg)返回false,即获取锁失败那就会执行acquireQueued(addWaiter(Node.EXCLUSIVE), arg)方法,其中Node.EXCLUSIVE指示节点正在排他模式中等待的标记。addWaiter方法则是快速尝试添加当前线程到CLH队列队尾并标记为独占模式:

    private Node addWaiter(Node mode) {
        //创建一个当前线程的node节点
        Node node = new Node(Thread.currentThread(), mode);
        // CLH队列尾节点
        Node pred = tail;
        if (pred != null) {
            node.prev = pred;
            if (compareAndSetTail(pred, node)) {
                pred.next = node;
                return node;
            }
        }
        enq(node);
        return node;
    }

此处判断pred!=null就是判断此链表是否已经初始化,如果已经初始化,即不为null,则此时通过CAS方法将tail设置为当前node对象:

    private final boolean compareAndSetTail(Node expect, Node update) {
        return unsafe.compareAndSwapObject(this, tailOffset, expect, update);
    }

这其中this表示AbstractQueuedSynchronizer的实例对象,tailOffset就是确认tail的位置,将符合期望的值赋值给tail。这个过程就是将未获取锁的线程放入链表中。

    private Node enq(final Node node) {
        for (;;) {
            Node t = tail;
            if (t == null) { // Must initialize
                if (compareAndSetHead(new Node()))
                    tail = head;
            } else {
                node.prev = t;
                if (compareAndSetTail(t, node)) {
                    t.next = node;
                    return t;
                }
            }
        }
    }

如果tail没有初始化,那么就会调用enq方法,这里循环先初始化tail、head,它们其实就是一个虚拟标志,然后继续循环添加未获取锁的线程到链表中。

那么这里有个问题

1)addWaiter方法中的代码,在enq中也存在这段代码,那么为什么还需要addWaiter方法呢?

在addWaiter方法中判断条件compareAndSetTail失败和pred ==null后才会进入到enq方法,在大部分并发情景之下,CAS操作几乎不会失败,所以addWaiter失败的数据很少,这样就可以节省很多条指令,提高效率。

主要是acquireQueued方法:

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

这个方法无论是公平锁还是非公平锁,都会调用同一个acquireQueued方法。

 final Node p = node.predecessor();

是获取前置节点,如果前置节点是head那么就尝试获取锁,这里所有等待的线程都是如此获取,但是他们出队的顺序是先进先出的,即排在头部的先尝试获取锁,那么非公平锁和公平锁的实现有什么不同,那肯定不是这个方法决定的。

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

这里shouldParkAfterFailedAcquire方法,判断一个waitStatus状态字段,其含义:

1:当前等待锁线程节点已取消/被中断(interrupt)

-1:当前线程节点释放锁时unpark唤醒next节点;

0:初始化等待节点,无下一等待节点

-2:条件等待condition执行signal/signalAll

-3:共享锁使用无条件传播

1):如果前继的节点状态为-1,表明当前节点需要unpark,则返回成功,此时acquireQueued方法的parkAndCheckInterrupt方法将线程阻塞;
2):如果前继节点状态为waitStatus>0,说明前置节点已经被放弃,则删除前继节点,返回false,acquireQueued方法的无限循环将递归调用该方法,第一步返回true,导致线程阻塞
3):如果前继节点状态为非-1、非1,则设置前继的状态为-1,返回false后进入acquireQueued的无限循环,直到第一步返回true,导致线程阻塞。

问题:

1)既然公平锁和非公平锁都是调用的acquireQueued方法,启动时都是从队列头部开始,那么为什么还有公平锁和非公平锁?

首先,这里的方法只是自旋时等待线程状态改变,然后唤醒在队列中等待获取锁的线程,这里虽然唤醒是有序的,但是获取锁的时候,由于cpu切换或者其他原因,还是会导致获取到锁的顺序不是队列中的顺序;

如下代码是非公平锁获取加锁的方式:

        protected final boolean tryAcquire(int acquires) {
            return nonfairTryAcquire(acquires);
        }
        final boolean nonfairTryAcquire(int acquires) {
            final Thread current = Thread.currentThread();
            int c = getState();
            if (c == 0) {
                if (compareAndSetState(0, acquires)) {
                    setExclusiveOwnerThread(current);
                    return true;
                }
            }
            else if (current == getExclusiveOwnerThread()) {
                int nextc = c + acquires;
                if (nextc < 0) // overflow
                    throw new Error("Maximum lock count exceeded");
                setState(nextc);
                return true;
            }
            return false;
        }

如下代码是公平锁获取锁的方法:

        protected final boolean tryAcquire(int acquires) {
            return nonfairTryAcquire(acquires);
        }
        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;
        }

此处公平锁与非公平锁的不同就是公平锁在在使用CAS获取锁之前多了一个hasQueuedPredecessors判断;

    public final boolean hasQueuedPredecessors() {
        // The correctness of this depends on head being initialized
        // before tail and on head.next being accurate if the current
        // thread is first in queue.
        Node t = tail; // Read fields in reverse initialization order
        Node h = head;
        Node s;
        return h != t &&
            ((s = h.next) == null || s.thread != Thread.currentThread());
    }

此方法就是判断当前线程是否是排在队列头部,如果是则返回false不是则返回true;由于获取锁时是&&,所以当不是当前队列首的数据,则会直接返回true,取非是false,所以就不会去获取锁,这样就实现了公平锁;

问题:

1)为什么在acquireQueued方法自旋的时候删除失效队列元素时删除pred,而不是next?

首先,目前很多回答是由于next不可靠。所以删除时通过pred来操作,那为什么next不可靠?

1.由于在开始node=tail的赋值过程中,node.next=null,此时使用compareAndSetTail(pred, node)设置的pred.next = null,如果此时又有线程进入,也会执行这一段代码,此时就会造成旧的tail的next是null但实际需要是非null,那么在unparkSuccessor中 node.next 就是null,会误以为等待队列中已经没有了正在等待的线程了。

    private Node addWaiter(Node mode) {
        Node node = new Node(Thread.currentThread(), mode);
        // Try the fast path of enq; backup to full enq on failure
        Node pred = tail;
        if (pred != null) {
            node.prev = pred;
            if (compareAndSetTail(pred, node)) {
                pred.next = node;
                return node;
            }
        }
        enq(node);
        return node;
    }

那么有会有问题,为什么不能先设置next在进行pred呢?

如果保证next先赋值,那么此时就无法确定tail的前一个节点是谁,就只能从前往后一直遍历出来,这样的效率肯定不如直接取来的高效。

 

 

 

 

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值