Lock以及AQS源码加理解

从一个自定义锁开始理解AQS

自定义锁

要使用一个自定义锁,要实现Lock接口,我们可以看到Lock中的方法都是基于Sync这个内部类的。所以自定义锁的时候我也创建了一内部类Sync,继承了AQS。
对于AQS,它提供了一堆模板方法,这些方法不需要我们实现,而只有5个方法我们可以重写,那就是:

  1. tryAcquire
  2. tryRelease
  3. tryAcquireShared
  4. tryReleaseShared
  5. isHeldExclusively
    对于最基本的使用,其实只要重写tryAcquire和tryRelease就可以

ReentrantLock可重入锁

RenntrantLock其实就是一个实现了Lock接口的类。它所做的也是我们上诉所说的实现了一个自定义锁。

从源码上理解ReentrantLock加锁

static ReentrantLock lock  = new ReentrantLock(); // 定义一个锁
lock.lock()

我们来尝试理解一下lock()这个方法它做了什么,这里先讨论非公平锁,因为默认是非公平锁

lock()
		final void lock() {
		// 这里就是CAS去想替换锁状态state为1,如果成功就会把独占锁的线程设置为当前线程
            if (compareAndSetState(0, 1))
                setExclusiveOwnerThread(Thread.currentThread());
            else
            // 替换失败,也就是竞争锁失败,调用acquire()方法
                acquire(1);
        }
acquire()
		public final void acquire(int arg) {
		// 尝试获取锁,tryAcquire
	        if (!tryAcquire(arg) &&
	        	// 这里是尝试获取锁失败了,那就用addWaiter方法把当前线程加入进同步队列
	        	// acquireQueued就是在队列中自旋尝试获取锁
	            acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
	            // 这里acquireQueued返回的就是中断标记,如果获取锁失败并且是被中断了,这里就自我中断一下,把中断标记为设置一下。
	            selfInterrupt();
	    }
    
		final boolean nonfairTryAcquire(int acquires) {
		 	// 获取当前线程
            final Thread current = Thread.currentThread();
            // 看一下当前线程的状态
            int c = getState();
            // 如果为0可以直接尝试获取
            if (c == 0) {
            	// 如果CAS成功就成功获取锁
                if (compareAndSetState(0, acquires)) {
                    setExclusiveOwnerThread(current);
                    return true;
                }
            }
            // 本身已经获得锁了
            else if (current == getExclusiveOwnerThread()) {
                // 因为是可重入的,所以这里把锁的请求加上
                int nextc = c + acquires;
                // 这里是爆int的意思
                if (nextc < 0) // overflow
                    throw new Error("Maximum lock count exceeded");
                // 这里不用CAS是因为本身线程已经有锁了
                setState(nextc);
                return true;
            }
            return false;
        }

		// 添加进入队列
		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;
	    }
		
		// 这是在等待队列里尝试获取锁
		final boolean acquireQueued(final Node node, int arg) {
			// 如果非正常状态退出,最后finally会cancel掉点前节点以及之前设置为cancel的节点
	        boolean failed = true;
	        try {
	        	// interrupt标志在parkAndCheckInterrupt会判断是否被中断
	            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;
	                }
	                // 返回失败的时候判断之前的节点是否为signal状态,signal状态说明前面节点都在等待中,那么此节点也肯定要等待,就随之把它park挂起。
	                if (shouldParkAfterFailedAcquire(p, node) &&
	                    parkAndCheckInterrupt())
	                    interrupted = true;
	            }
	        } finally {
	            if (failed)
	                cancelAcquire(node);
	        }
	    }

		private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
			// 获取前驱节点的状态
	        int ws = pred.waitStatus;
	        // 如果是SIGNAL说明前驱节点也在等待signal,那么就说明这个节点肯定也要等待,所以挂起
	        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.
	             */
	             
				// 循环将前驱的为cancel的全部给删掉
	            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.
	             */
	            
	            // 如果前驱节点为其他的状态,那么就设置为SIGNAL状态
	            compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
	        }
        	return false;
   	 	}
	

公平锁

公平锁的区别主要就是在第一次tryAcquire的时候要判断hasQueuedPredecessors,其实也就是判断是否有在head之后的节点在等着,并且还不是当前的节点

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

Node的状态

    static final Node SHARED = new Node();
    /** Marker to indicate a node is waiting in exclusive mode */
    static final Node EXCLUSIVE = null;

    /** waitStatus value to indicate thread has cancelled */
    static final int CANCELLED =  1;
    /** waitStatus value to indicate successor's thread needs unparking */
    static final int SIGNAL    = -1;
    /** waitStatus value to indicate thread is waiting on condition */
    static final int CONDITION = -2;
    /**
     * waitStatus value to indicate the next acquireShared should
     * unconditionally propagate
     */
    static final int PROPAGATE = -3;

在上面的源码中基本上就把ReentrantLock的lock方法获得锁的模式给解释清楚了。
ReentrantLock还提供了其他方法比如:

  1. tryLock:这个方法其实就是调用了之前说的tryLock,就只是进行一次获取锁,获取失败就返回
  2. tryLock(timeout, unit) //这是一个超时方法,它会对中断敏感,它所做的就是在超时时间内获取锁
  3. lockInterruptibly() // 这也是支持中断的加锁方法,它和上面这个方法的区别就在于,上面的支持超时也支持中断,而这个不行
  4. isHeldByCurrentThread() 返回当前线程是否获得了锁

从源码上理解ReentrantLock释放锁

unlock()
release(int arg)
		public final boolean release(int arg) {
			// 尝试释放锁
	        if (tryRelease(arg)) {
	        	// 
	            Node h = head;
	            if (h != null && h.waitStatus != 0)
	                unparkSuccessor(h);
	            return true;
	        }
	        return false;
	    }
	    
		protected final boolean tryRelease(int releases) {
			// 把release的请求减去
            int c = getState() - releases;
            // 如果当前的线程不是拥有锁的线程,出大问题,抛异常
            if (Thread.currentThread() != getExclusiveOwnerThread())
                throw new IllegalMonitorStateException();
            // 看是否成功释放的标志
            boolean free = false;
            // 如果全部释放完了,那才是成功释放
            if (c == 0) {
                free = true;
                // 把锁的拥有者设置为null
                setExclusiveOwnerThread(null);
            }
            // 重新设置一下c,这里也是因为有控制权所以不用CAS
            setState(c);
            // 返回是否释放了锁的所有权
            return free;
        }
		
		// 释放后继
		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.
	         */
			// 从后往前遍历,找到下一个状态为SIGNAL的节点
	        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);
	    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中的AQS(AbstractQueuedSynchronizer)是实现锁和同步器的一种重要工具。在AQS中,一个节点表示一个线程,依次排列在一个双向队列中,同时使用CAS原子操作来保证线程安全。当多个线程对于同一资源竞争时,一个节点会被放置在队列的尾部,其他线程则在其之前等待,直到该资源可以被锁定。 当一个线程调用lock()方法进行锁定时,它会首先调用tryAcquire()方法尝试获取锁。如果当前资源尚未被锁定,则该线程成功获取锁,tryAcquire()返回true。如果当前资源已被锁定,则线程无法获取锁,tryAcquire()返回false。此时该线程就会被入到等待队列中,同时被入到前一个节点的后置节点中,即成为它的后继。然后该线程会在park()方法处等待,直到前一个节点释放了锁,再重新尝试获取锁。 在AQS中,当一个节点即将释放锁时,它会调用tryRelease()方法来释放锁,并唤醒后置节点以重试获取锁。如果当前节点没有后置节点,则不会发生任何操作。当一个线程在队列头部成功获取锁和资源时,该线程需要使用release()方法释放锁和资源,并唤醒等待队列中的后置节点。 总之,AQS中的锁机制是通过双向等待队列实现的,其中节点表示线程,使用CAS原子操作保证线程安全,并在tryAcquire()和tryRelease()方法中进行锁定和释放。该机制保证了多线程环境下资源的正确访问和线程的安全执行。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值