资讯专栏INFORMATION COLUMN

Java并发核心浅谈(二)

Null / 993人阅读

摘要:在线程处理任务期间,其它线程要么循环访问,要么一直阻塞等着线程唤醒,再不济就真的如我所说,放弃锁的竞争,去处理别的任务。写锁的话,独占写计数,排除一切其他线程。

回顾

在上一篇 Java并发核心浅谈 我们大概了解到了Locksynchronized的共同点,再简单总结下:

Lock主要是自定义一个 counter,从而利用CAS对其实现原子操作,而synchronizedc++ hotspot实现的 monitor(具体的咱也没看,咱就不说)

二者都可重入(递归,互调,循环),其本质都是维护一个可计数的 counter,在其它线程访问加锁对象时会判断 counter 是否为 0

理论上讲二者都是阻塞式的,因为线程在拿锁时,如果拿不到,最终的结果只能等待(前提是线程的最终目的就是要获取锁)读写锁分离成两把锁了,所以不一样

举个例子:线程 A 持有了某个对象的 monitor,其它线程在访问该对象时,发现 monitor 不为 0,所以只能阻塞挂起或者加入等待队列,等着线程 A 处理完退出后将 monitor 置为 0。在线程 A 处理任务期间,其它线程要么循环访问 monitor,要么一直阻塞等着线程 A 唤醒,再不济就真的如我所说,放弃锁的竞争,去处理别的任务。但是应该做不到去处理别的任务后,任务处理到一半,被线程 A 通知后再回去抢锁

公平锁与非公平锁

不共享 counter

        // 非公平锁在第一次拿锁失败也会调用该方法
        public final void acquire(int arg) {
        // 没拿到锁就加入队列
        if (!tryAcquire(arg) &&
            acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
            selfInterrupt();
        }
        
        // 非公平锁方法
        final void lock() {
            // 走来就尝试获取锁
            if (compareAndSetState(0, 1))
                setExclusiveOwnerThread(Thread.currentThread());
            else
                acquire(1); // 上面那个方法
        }
        
        // 公平锁 Acquire 计数
        protected final boolean tryAcquire(int acquires) {
            final Thread current = Thread.currentThread();
            // 拿到计数
            int c = getState();
            if (c == 0) {
                // 公平锁会先尝试排队 非公平锁少个 !hasQueuedPredecessors() 其它代码一样
                if (!hasQueuedPredecessors() &&
                    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;
        }
        
        /**
         * @return {@code true} if there is a queued thread preceding the // 当前线程前有线程等待,则排队
         *         current thread, and {@code false} if the current thread
         *         is at the head of the queue or the queue is empty // 队列为空不用排队
         * @since 1.7
         */
        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());
        }
        
        // 加入等待队列
        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;
                }
                // 获取失败会检查节点状态
                // 然后 park 线程
                if (shouldParkAfterFailedAcquire(p, node) &&
                    parkAndCheckInterrupt())
                    interrupted = true;
            }
        } finally {
            if (failed)
                cancelAcquire(node);
        }
    }
    
        /** 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;  // 解除线程 park
        /** 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; // 广播
        
        // 官方注释
        /**
         * Status field, taking on only the values:
         *   SIGNAL:     The successor of this node is (or will soon be)
         *               blocked (via park), so the current node must
         *               unpark its successor when it releases or
         *               cancels. To avoid races, acquire methods must
         *               first indicate they need a signal,
         *               then retry the atomic acquire, and then,
         *               on failure, block.
         *   CANCELLED:  This node is cancelled due to timeout or interrupt.
         *               Nodes never leave this state. In particular,
         *               a thread with cancelled node never again blocks.
         *   CONDITION:  This node is currently on a condition queue.
         *               It will not be used as a sync queue node
         *               until transferred, at which time the status
         *               will be set to 0. (Use of this value here has
         *               nothing to do with the other uses of the
         *               field, but simplifies mechanics.)
         *   PROPAGATE:  A releaseShared should be propagated to other
         *               nodes. This is set (for head node only) in
         *               doReleaseShared to ensure propagation
         *               continues, even if other operations have
         *               since intervened.
         *   0:          None of the above
         *
         * The values are arranged numerically to simplify use.
         * Non-negative values mean that a node doesn"t need to
         * signal. So, most code doesn"t need to check for particular
         * values, just for sign.
         *
         * The field is initialized to 0 for normal sync nodes, and
         * CONDITION for condition nodes.  It is modified using CAS
         * (or when possible, unconditional volatile writes).
         */
        volatile int waitStatus;
读锁与写锁(共享锁与排他锁)

读锁:共享 counter

写锁:不共享 counter

        // 读写锁和线程池的类似之处
        // 高 16 位为读计数,低 16 位为写计数
        static final int SHARED_SHIFT   = 16;
        static final int SHARED_UNIT    = (1 << SHARED_SHIFT);
        static final int MAX_COUNT      = (1 << SHARED_SHIFT) - 1;
        static final int EXCLUSIVE_MASK = (1 << SHARED_SHIFT) - 1;

        /** Returns the number of shared holds represented in count. */ // 获取读计数
        static int sharedCount(int c)    { return c >>> SHARED_SHIFT; }
        /** Returns the number of exclusive holds represented in count. */ // 获取写计数
        static int exclusiveCount(int c) { return c & EXCLUSIVE_MASK; }
        
        /**
         * A counter for per-thread read hold counts. 每个线程自己的读计数
         * Maintained as a ThreadLocal; cached in cachedHoldCounter.
         */
        static final class HoldCounter {
            int count;          // initially 0
            // Use id, not reference, to avoid garbage retention
            final long tid = LockSupport.getThreadId(Thread.currentThread()); // 线程 id
        }
        
    // 尝试获取读锁
    protected final int tryAcquireShared(int unused) {
            // ReentrantReadWriteLock ReadLock 读锁
            /*
             * Walkthrough:
             * 1. If write lock held by another thread, fail.
             * 2. Otherwise, this thread is eligible for
             *    lock wrt state, so ask if it should block
             *    because of queue policy. If not, try
             *    to grant by CASing state and updating count.
             *    Note that step does not check for reentrant
             *    acquires, which is postponed to full version
             *    to avoid having to check hold count in
             *    the more typical non-reentrant case.
             * 3. If step 2 fails either because thread
             *    apparently not eligible or CAS fails or count
             *    saturated, chain to version with full retry loop.
             */
            Thread current = Thread.currentThread();
            int c = getState();
            // 如果写锁计数不为零,且当前线程不是写锁持有线程,则可以获得读锁
            // 言外之意,获得写锁的线程不可以再获得读锁
            // 个人认为不用判断写计数也行
            if (exclusiveCount(c) != 0 &&
                getExclusiveOwnerThread() != current)
                return -1;
            // 获得读计数
            int r = sharedCount(c);
            // 检查等待队列 读计数上限
            if (!readerShouldBlock() &&
                r < MAX_COUNT &&
                // 在高 16 位更新
                compareAndSetState(c, c + SHARED_UNIT)) {
                if (r == 0) {
                    firstReader = current;
                    firstReaderHoldCount = 1;
                } else if (firstReader == current) {
                    firstReaderHoldCount++;
                } else {
                    HoldCounter rh = cachedHoldCounter;
                    if (rh == null ||
                        rh.tid != LockSupport.getThreadId(current))
                        // cachedHoldCounter 每个线程自己的读计数,非共享。但是锁计数与其它读操作共享,不与写操作共享
                        // readHolds 为ThreadLocalHoldCounter,继承于 ThreadLocal,存 cachedHoldCounter
                        cachedHoldCounter = rh = readHolds.get();
                    else if (rh.count == 0)
                        readHolds.set(rh);
                    rh.count++;
                }
                return 1;
            }
            // 说明在排队中,就一直遍历,直到队首,实际起作用的代码和上面代码差不多
            // 大师本人也说了代码有冗余
             /*
             * This code is in part redundant with that in
             * tryAcquireShared but is simpler overall by not
             * complicating tryAcquireShared with interactions between
             * retries and lazily reading hold counts.
             */
            return fullTryAcquireShared(current);
        }
        
    // 获得写锁  
    protected final boolean tryAcquire(int acquires) {
            /*
             * Walkthrough:
             * 1. If read count nonzero or write count nonzero
             *    and owner is a different thread, fail. 
             * 读锁不为零(读锁排除写锁,但是与读锁共享)
             * 写锁不为零且锁持有者不为当前线程,则获得锁失败
             * 2. If count would saturate, fail. (This can only
             *    happen if count is already nonzero.) // 计数器已达最大值,获得锁失败
             * 3. Otherwise, this thread is eligible for lock if
             *    it is either a reentrant acquire or
             *    queue policy allows it. If so, update state
             *    and set owner. // 重入是可以的;队列策略也是可以的,会在下面解释
             */
            Thread current = Thread.currentThread();
            int c = getState();
            // 获得写计数
            int w = exclusiveCount(c);
            if (c != 0) {
                // (Note: if c != 0 and w == 0 then shared count != 0)
                // 检查所持有线程
                if (w == 0 || current != getExclusiveOwnerThread())
                    return false;
                // 检查最大计数
                if (w + exclusiveCount(acquires) > MAX_COUNT)
                    throw new Error("Maximum lock count exceeded");
                // Reentrant acquire 线程重入获得锁,直接更新计数
                setState(c + acquires);
                return true;
            }
            // 队列策略
            // state 为 0,检查是否需要排队
            // 针对公平锁:去排队,如果当前线程在队首或等待队列为空,则返回 false,自然会走后面的 CAS
            // 否则就返回 true,则进入 return false;
            // 针对非公平锁:写死为 false,直接 CAS
            if (writerShouldBlock() ||
                !compareAndSetState(c, c + acquires))
                return false;
            // 设置当前写锁持有线程
            setExclusiveOwnerThread(current);
            return true;
        }    
    
    // 因为读锁是多个线程共享读计数,各自维护了自己的读计数,所以释放的时候比写锁释放要多些操作
     protected final boolean tryReleaseShared(int unused) {
            Thread current = Thread.currentThread();
            // 当前线程是第一读线程的操作
            // firstReader 作为字段缓存,是考虑到第一次读的线程使用率高?
            if (firstReader == current) {
                // assert firstReaderHoldCount > 0;
                if (firstReaderHoldCount == 1)
                    firstReader = null;
                else
                    firstReaderHoldCount--;
            } else {
                HoldCounter rh = cachedHoldCounter;
                if (rh == null ||
                    rh.tid != LockSupport.getThreadId(current))
                    rh = readHolds.get();
                int count = rh.count;
                if (count <= 1) {
                    readHolds.remove();
                    if (count <= 0)
                        throw unmatchedUnlockException();
                }
                --rh.count;
            }
            for (;;) {
                int c = getState();
                int nextc = c - SHARED_UNIT;
                if (compareAndSetState(c, nextc))
                    // Releasing the read lock has no effect on readers,
                    // but it may allow waiting writers to proceed if
                    // both read and write locks are now free.
                    return nextc == 0;
            }
        }
总结一下

公平锁和非公平锁的“锁”实现是基于CAS,公平性基于内部维护的Node链表

读写锁,可以粗略的理解为读和写两种状态,所以这儿的设计类似线程池的状态。只不过,读计数是可以多个读线程共享的(排除写锁),每个读的线程都会维护自己的读计数。写锁的话,独占写计数,排除一切其他线程。

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/77772.html

相关文章

  • Java并发核心浅谈

    摘要:耐心看完的你或多或少会有收获并发的核心就是包,而的核心是抽象队列同步器,简称,一些锁啊信号量啊循环屏障啊都是基于。 耐心看完的你或多或少会有收获! Java并发的核心就是 java.util.concurrent 包,而 j.u.c 的核心是AbstractQueuedSynchronizer抽象队列同步器,简称 AQS,一些锁啊!信号量啊!循环屏障啊!都是基于AQS。而 AQS 又是...

    cppowboy 评论0 收藏0
  • 浅谈Java并发编程系列()—— Java内存模型

    摘要:物理计算机并发问题在介绍内存模型之前,先简单了解下物理计算机中的并发问题。基于高速缓存的存储交互引入一个新的问题缓存一致性。写入作用于主内存变量,把操作从工作内存中得到的变量值放入主内存的变量中。 物理计算机并发问题 在介绍Java内存模型之前,先简单了解下物理计算机中的并发问题。由于处理器的与存储设置的运算速度有几个数量级的差距,所以现代计算机加入一层读写速度尽可能接近处理器的高速缓...

    Edison 评论0 收藏0
  • 浅谈Java并发编程系列(一)—— 如何保证线程安全

    摘要:比如需要用多线程或分布式集群统计一堆用户的相关统计值,由于用户的统计值是共享数据,因此需要保证线程安全。如果类是无状态的,那它永远是线程安全的。参考探索并发编程二写线程安全的代码 线程安全类 保证类线程安全的措施: 不共享线程间的变量; 设置属性变量为不可变变量; 每个共享的可变变量都使用一个确定的锁保护; 保证线程安全的思路: 1. 通过架构设计 通过上层的架构设计和业务分析来避...

    mylxsw 评论0 收藏0
  • 浅谈Java并发编程系列(六) —— 线程池的使用

    摘要:线程池的作用降低资源消耗。通过重复利用已创建的线程降低线程创建和销毁造成的资源浪费。而高位的部分,位表示线程池的状态。当线程池中的线程数达到后,就会把到达的任务放到中去线程池的最大长度。默认情况下,只有当线程池中的线程数大于时,才起作用。 线程池的作用 降低资源消耗。通过重复利用已创建的线程降低线程创建和销毁造成的资源浪费。 提高响应速度。当任务到达时,不需要等到线程创建就能立即执行...

    Vicky 评论0 收藏0
  • 后台开发常问面试题集锦(问题搬运工,附链接)

    摘要:基础问题的的性能及原理之区别详解备忘笔记深入理解流水线抽象关键字修饰符知识点总结必看篇中的关键字解析回调机制解读抽象类与三大特征时间和时间戳的相互转换为什么要使用内部类对象锁和类锁的区别,,优缺点及比较提高篇八详解内部类单例模式和 Java基础问题 String的+的性能及原理 java之yield(),sleep(),wait()区别详解-备忘笔记 深入理解Java Stream流水...

    spacewander 评论0 收藏0

发表评论

0条评论

Null

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<