源码解析之——ReentrantLock

ReentrantLock的使用

Lock lock = new ReentrantLock();
lock.lock();
try {
 doSomething();
}finally {
 lock.unlock();
}

lock.lock () 就是在显式的上锁。上锁后,下面的代码块一定要放到 try 中,并且要结合 finally 代码块调用 lock.unlock () 来释放锁,否则一定 doSomething 方法中出现任何异常,这个锁将永远不会被释放掉。

ReentrantLock支持公平和非公平锁两种形式,在声明的时候传入true,则为公平锁。

上面Lock.lock的方式获取的锁,是一种阻塞的方式加锁,即直到获取锁才会继续向下进行。
还有一种tryLock的方法获取锁,这个方法有两个重载,第一个是无参的tryLock方法,被调用后,该方法会立即返回获取锁的情况。获取为 true,未能获取为 false。第二个是有参数的 tryLock 方法,通过传入时间和单位,来控制等待获取锁的时长。如果超过时间未能获取锁则放回 false,反之返回 true。

源码分析

1、lock方法

public void lock() {
    //ReentrantLock通过内置的sync对象加锁
        sync.lock();
}

sync对象在renentrantlock的构造函数中已经给赋值,即赋值为公平的sync和非公平的 sync

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

在这里插入图片描述
再来看NonfairSync和fairSync中的lock方法实现:

公平锁


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

方法最后会执行一个acquire(1);方法去尝试获取锁。acquire方法处于独占模式,通过调用tryAcquire来实现,成功后返回,否则将会被放入到队列中,反复尝试获取锁,直到tryAcquire成功。

public final void acquire(int arg) {
        if (!tryAcquire(arg) &&
            acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
            selfInterrupt();
}
/**
         * 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();
            // 获取AQS中锁的状态
            int c = getState();
            // 如果锁目前是自由状态
            if (c == 0) {
                // 因为是公平锁,所以hasQueuedPredecessors()会先判断队列中是否有其他线程早于当前线程等待
                if (!hasQueuedPredecessors() &&
                    compareAndSetState(0, acquires)) {//执行cas操作,将aqs中state的状态 改为1(非自由状态)
                    // 设置当前线程为独占访问的线程
                    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;
        }

在这里插入图片描述

// 判断队列中是否有其他线程早于当前线程等待
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());
    }
 // 如果当前状态值等于预期值,则自动将同步状态设置为给定的更新值。该操作具有{@code volatile}读写的内存语义。
protected final boolean compareAndSetState(int expect, int update) {
        // See below for intrinsics setup to support this
        // 拿到aqs中state的值,与期望值进行比较,如果相等,执行更新操作
        return unsafe.compareAndSwapInt(this, stateOffset, expect, update);
    }
// 设置当前线程为独占访问的线程   
protected final void setExclusiveOwnerThread(Thread thread) {
        exclusiveOwnerThread = thread;
    }

在这里插入图片描述
如果在tryAcquire方法中返回true,说明当前线程已经获得锁,并且是独占状态,直接返回继续执行同步代码,如果返回false,说明当前锁已经被其他线程持有,将会尝试执行addWaiter下面的方法,将当前线程封装一个等待node,加入到队列中进行排队,然后调用acquireQueued 尝试排队获取锁:

/**
     * Creates and enqueues node for current thread and given mode.
     *
     * @param mode Node.EXCLUSIVE for exclusive, Node.SHARED for shared
     * @return the new node
     */
//将当前线程封装成一个节点,放入队列中
    private Node addWaiter(Node mode) {
        Node node = new Node(Thread.currentThread(), mode);
        // Try the fast path of enq; backup to full enq on failure
        //将队尾复制给pred
        Node pred = tail;
        // 判断pred是否为空(判断队尾是否有节点),if语句成立说明队列已经初始化了,已经有线程在排队了
        if (pred != null) {
            // 如果队尾有节点,将当前节点的头指针指向队尾节点
            node.prev = pred;
            // //这里需要cas,因为防止多个线程加锁,确保nc入队的时候是原子操作
            if (compareAndSetTail(pred, node)) {
                // 把pred的下一个节点设置为当前节点,这个nc自己成为对尾了
                pred.next = node;
                return node;
            }
        }
        // if不成立说明队列还没有初始化,此时还没有线程在排队,则初始化队列,将当前线程作为尾结点放入队列中
        enq(node);
        return node;
    }
/**
     * Inserts node into queue, initializing if necessary. See picture above.
     * @param node the node to insert
     * @return node's predecessor
     */
    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;
                }
            }
        }
    }
//队列中的线程不断查看自己的排队情况
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状态也就是-1状态。(每个节点都有一个状态,默认为0,表示无状态,-1标识在park。为了防止变动,节点要先变成park状态后才能将标识改成-1,但是如果节点已经是park状态了,就完全释放CPU资源了,不能执行任何代码,所以需要他的后一个节点将前一个节点改成-1状态)
            if (shouldParkAfterFailedAcquire(p, node) && //改上一个节点的状态成功之后;自己park;
                parkAndCheckInterrupt())
                interrupted = true;
        }
    } finally {
        if (failed)
            cancelAcquire(node);
    }
}
整个获取锁的过程我们可以总结下:
  1. 直接通过 tryAcquire 尝试获取锁,成功直接返回;
  2. 如果没能获取成功,那么把自己加入等待队列;
  3. 自旋查看自己的排队情况;
  4. 如果排队轮到自己,那么尝试通过 tryAcquire 获取锁;
  5. 如果没轮到自己,那么回到第三步查看自己的排队情况。

非公平锁

对于非公平锁,在执行lock方法时,会立即尝试获得锁,失败时才备份到正常的获取

/**
     * Sync object for non-fair locks
     */
    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);
        }

        // 非公平锁的 tryAcquire方法实现与公平锁是不一样的,如下
        protected final boolean tryAcquire(int acquires) {
            return nonfairTryAcquire(acquires);
        }
    }

/**
         * Performs non-fair tryLock.  tryAcquire is implemented in
         * subclasses, but both need nonfair try for trylock method.
         */
        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;
        }

在这里插入图片描述
在这里插入图片描述

2、unLock方法

public void unlock() {
    sync.release(1);
}
 public final boolean release(int arg) {
     // 如果当前锁状态为0,即释放锁成功,那么则会通过 unparkSuccessor 方法找到队列中第一个 waitStatus<0 的线程进行唤醒
        if (tryRelease(arg)) {
            Node h = head;
            // 如果头结点不为空,并且初始化条件不为0,尝试唤醒头结点的后继节点
            if (h != null && h.waitStatus != 0)
                // 尝试唤醒头结点的后继节点
                unparkSuccessor(h);
            return true;
        }
        return false;
    }

protected final boolean tryRelease(int releases) {
    		// 释放锁的时候需要对原来的锁状态进行减一操作,直到减为0的时候,返回当前锁的状态为0(自由状态)
            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;
        }

总结:

ReentrantLock 的设计思想是通过 FIFO 的队列保存等待锁的线程。通过 volatile 类型的 state 保存锁的持有数量,从而实现了锁的可重入性。而公平锁则是通过判断自己是否排队成功,来决定是否去争抢锁。

ReentrantLock与Synchronized的区别

1、实现的机制不同,synchronized是JVM级别的关键字,而ReenTrantLock是类级别的。
2、ReentrantLock是非常灵活的,能够选择什么时候获得锁什么时候释放锁。但是Synchronized锁的获得和释放是被动的,只有当同步代码块执行结束或者出现异常的时候才会释放锁。
3、ReentrantLock可以判断锁的状态。
4、对于ReentrantLock来说有公平锁和非公平锁之说,但是Synchronized是一个非公平锁。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
ConcurrentHashMap是Java中并发访问的哈希表实现,它在多线程环境下提供了高效的并发操作。 在JDK 1.8中,ConcurrentHashMap的实现基于数组和链表结构,同时引入了红黑树来提高性能。下面是对ConcurrentHashMap的源码解析: 1. 分段锁:ConcurrentHashMap中使用了分段锁(Segment)的机制,将整个数据结构分成多个Segment。每个Segment维护了一部分键值对,它们之间是相互独立的。这样在并发访问时,只需要锁住对应的Segment,不同的Segment可以并发执行,极大地提高了并发访问的效率。 2. 数据结构:ConcurrentHashMap内部使用了一个由Segment数组组成的table来存储数据。每个Segment都是一个独立的哈希表,继承自ReentrantLock来保证线程安全。每个Segment中包含一个HashEntry数组,每个HashEntry是一个链表或红黑树的节点。 3. put操作:当进行put操作时,首先计算键的哈希值,然后通过哈希值的高位和Segment数组长度进行运算,确定需要操作的Segment。在对应的Segment中进行插入操作,使用lock()方法获取Segment对应的锁。如果插入时发现链表过长(默认阈值为8),会将链表转换为红黑树,提高插入和查找的速度。如果插入的键已存在,会更新对应的值。 4. get操作:当进行get操作时,也首先计算键的哈希值,然后确定需要操作的Segment。在对应的Segment中进行查找操作,使用lock()方法获取Segment对应的锁。在链表或红黑树中查找键对应的值。 5. remove操作:当进行remove操作时,同样需要计算键的哈希值,确定需要操作的Segment。在对应的Segment中进行删除操作,使用lock()方法获取Segment对应的锁。在链表或红黑树中查找键,并删除对应的节点。 总结来说,ConcurrentHashMap通过分段锁和内部数据结构的优化,在多线程环境下提供了高效的并发访问。它支持高并发的插入、查找和删除操作,同时保证数据的一致性和正确性。但需要注意,在遍历ConcurrentHashMap时,由于Segements之间是独立的,可能会存在一些不一致的情况,因此在遍历时需谨慎。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值