微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ReentrantLock源码之公平锁的实现

public class reentrantlockDemo {

    public static void main(String[] args) {
        reentrantlock reentrantlock = new reentrantlock(true);
        reentrantlock.lock();
        reentrantlock.unlock();
    }

}
    public reentrantlock() {
        sync = new Nonfairsync();    // new了1个非公平实现
    }
  • 查看sync

  • 查看有参构造

    public reentrantlock(boolean fair) {
        sync = fair ? new Fairsync() : new Nonfairsync();    // 为true时返回公平实现,否则返回非公平实现
    }

public class reentrantlockDemo {

    public static void main(String[] args) {
        reentrantlock reentrantlock = new reentrantlock(true);
        reentrantlock.lock();
        reentrantlock.unlock();
    }

}

public void lock() {
    sync.acquire(1);
}

public final void acquire(int arg) {
    // 尝试获取锁
    if (!tryAcquire(arg) &&
        acquireQueued(addWaiter(Node.EXCLUSIVE), arg))    // 同时获取队列失败
        selfInterrupt();      // 则线程终止
}
    protected boolean tryAcquire(int arg) {
        throw new UnsupportedOperationException();
    }
  • 查看非公平实现

static final class Nonfairsync extends Sync {
    private static final long serialVersionUID = 7316153563782823691L;
    protected final boolean tryAcquire(int acquires) {
        return nonfairTryAcquire(acquires);
    }
}

@ReservedStackAccess
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;    // 重入状态加1
        if (nextc < 0) // overflow      // 超过最大重入状态,抛出异常
            throw new Error("Maximum lock count exceeded");
        setState(nextc);    // 更新
        return true;    // 获得锁
    }
    return false;
}
    public final void acquire(int arg) {
        if (!tryAcquire(arg) &&
            acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
            selfInterrupt();
    }
  • 查看EXCLUSIVE

  • 查看addWaiter方法

    private Node addWaiter(Node mode) {
        Node node = new Node(mode);    // 传入参数,当前线程,new1个Node

        for (;;) {
            Node oldTail = tail;    // 前置节点指向尾节点
            if (oldTail != null) {
                node.setPrevRelaxed(oldTail);
                if (compareAndSetTail(oldTail, node)) {    // node设置为尾节点
                    oldTail.next = node;
                    return node;
                }
            } else {
                initializeSyncQueue();    // 若整条队列为null,执行入队
            }
        }
    }
  • 查看Node
Node(Node nextWaiter) {
    this.nextWaiter = nextWaiter;
    THREAD.set(this, Thread.currentThread());
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐