码迷,mamicode.com
首页 > 其他好文 > 详细

ReentrantLock

时间:2018-07-28 19:37:03      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:stat   immediate   公平锁与非公平锁   lse   false   进入   方法   forms   线程   

目录

ReentrantLock(基于jdk1.8)

ReentrantLock 可重入锁, 支持重进入的锁; 表示该锁能够支持一个线程对资源的重复加锁; 除此之外, 该锁还支持获取锁时的公平和非公平选择;

公平锁与非公平锁

  • 公平锁: 在绝对时间上, 先对锁进行获取请求的一定先被满足, 则为公平锁, 公平锁可以减少饥饿的发生;
  • 非公平锁: 获取锁的先后与对锁进行获得请求的先后没有必然的关系, 则为非公平锁;
  • 公平锁机制效率比非公平锁低;

相关笔记

一、 ReentrantLock中可重入的实现

重入: 是指任意线程在获取到锁之后能够再次获取该锁而不会被锁所阻塞;

实现重入需要解决的两个问题:

  • 线程再次获取锁: 锁需要去识别获取锁的线程是否为当前线程, 如果是, 则再获取成功;
  • 锁的最终释放: 锁重复获取了n次, 要在随后的第n次释放后, 其他线程能够获取该锁;

ReentrantLock的内部类Sync的可重入实现:

// 获取state, state为0, 表示当前线程第一次获取锁, 使用CAS设值state
// state不为0, 表示当前线程进行了重入, 将之前的state与acquires相加, 然后更新state
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;
}

二、 ReentrantLock同步器Sync的实现

NonfairSync, FairSync 都是继承自Sync

abstract static class Sync extends AbstractQueuedSynchronizer {
    private static final long serialVersionUID = -5179523762034025860L;

    /**
     * Performs {@link Lock#lock}. The main reason for subclassing
     * is to allow fast path for nonfair version.
     */
    abstract void lock(); // 交由子类实现

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

    // 释放锁
    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;
    }

    protected final boolean isHeldExclusively() {
        // While we must in general read state before owner,
        // we don't need to do so to check if current thread is owner
        return getExclusiveOwnerThread() == Thread.currentThread();
    }

    final ConditionObject newCondition() {
        return new ConditionObject();
    }

    // Methods relayed from outer class
    // 获取正在运行的线程
    final Thread getOwner() {
        return getState() == 0 ? null : getExclusiveOwnerThread();
    }

    // 获取当前线程持有的资源数 
    final int getHoldCount() {
        return isHeldExclusively() ? getState() : 0;
    }

    final boolean isLocked() {
        return getState() != 0;
    }

    /**
     * Reconstitutes the instance from a stream (that is, deserializes it).
     */
    private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOException, ClassNotFoundException {
        s.defaultReadObject();
        setState(0); // reset to unlocked state
    }
}

三、 NonfairSync(非公平锁)的实现

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

四、FairSync(公平锁)的实现

公平锁与非公平锁的实现相比, 多加了一个hasQueuedPredecessors()判断;
即加入了同步队列中当前节点是否有前继节点的判断,如果该方法返回true, 表示有线程比当前线程更早的请求锁,此时需要等待前驱节点释放锁之后才能继续获取锁;

static final class FairSync extends Sync {
        private static final long serialVersionUID = -3000897897090466540L;

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

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

五、 ReentrantLock对Lock接口方法的重写

public class ReentrantLock implements Lock, java.io.Serializable {
    private static final long serialVersionUID = 7373984872572414699L;
    /** Synchronizer providing all implementation mechanics */
    private final Sync sync;

    public void lock() {
        sync.lock();
    }
    public void lockInterruptibly() throws InterruptedException {
        sync.acquireInterruptibly(1);
    }
    public boolean tryLock() {
        return sync.nonfairTryAcquire(1);
    }
    public boolean tryLock(long timeout, TimeUnit unit)
            throws InterruptedException {
        return sync.tryAcquireNanos(1, unit.toNanos(timeout));
    }
    public void unlock() {
        sync.release(1);
    }
    public Condition newCondition() {
        return sync.newCondition();
    }

ReentrantLock

标签:stat   immediate   公平锁与非公平锁   lse   false   进入   方法   forms   线程   

原文地址:https://www.cnblogs.com/jxkun/p/9383056.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!