从ReentrantLock的实现看AQS的原理

前言

Java中的大部分同步类(Lock、Semaphore、ReentrantLock等)都是基于AbstractQueuedSynchronizer(简称为AQS)实现的。

AQS简介
  • AQS是一种提供了原子式管理同步状态、阻塞和唤醒线程功能以及队列模型的简单框架
  • 核心思想是,如果被请求的共享资源空闲,那么就将当前请求资源的线程设置为有效的工作线程,将共享资源设置为锁定状态;如果共享资源被占用,就需要一定的阻塞等待唤醒机制来保证锁分配。这个机制主要用的是CLH队列的变体实现的,将暂时获取不到锁的线程加入到队列中
  • CLH:Craig、Landin and Hagersten队列,是单向链表,AQS中的队列是CLH变体的虚拟双向队列(FIFO),AQS是通过将每条请求共享资源的线程封装成一个节点来实现锁的分配。
  • AQS使用的是模板设计模式,使用者只需要实现里面的模板方法就可以,其它内部都已经被AQS实现,外面不必关心
  • 模板方法有二对:tryAcquire–tryRelease; tryAcquireShared–tryReleaseShared
  • AQS里面最重要的一个成员变量state,是否执有锁都跟这个有关
根据AQS源码,自已创建一个AbstractQueuedSynchronizerTest 类,方便Debug
public abstract class AbstractQueuedSynchronizerTest extends AbstractOwnableSynchronizer implements java.io.Serializable {
	//AQS里面维护的是一个双向队列所里面面有二个成员变量
	private transient volatile Node head; // 虚拟头节点
    private transient volatile Node tail; // 虚拟尾节点
    
    private volatile int state;	// 最重要的一个成员变量
    // 模板方法有 
    //tryAcquire和tryRelease这一对是独占模式  tryAcquireShared和tryReleaseShared这一对是共享模式
    
	// 尝试获取资源,成功则返回True,失败则返回False。
    protected boolean tryAcquire(int arg) {
        throw new UnsupportedOperationException();
    }
    // 尝试释放资源,成功则返回True,失败则返回False。
    protected boolean tryRelease(int arg) {
        throw new UnsupportedOperationException();
    }
	
	// 尝试获取资源。负数表示失败;0表示成功,但没有剩余可用资源;正数表示成功,且有剩余资源。
    protected int tryAcquireShared(int arg) {
        throw new UnsupportedOperationException();
    }
	// 尝试释放资源,如果释放后允许唤醒后续等待结点返回True,否则返回False。
    protected boolean tryReleaseShared(int arg) {
        throw new UnsupportedOperationException();
    }
    
}

ReentrantLock

定义
  • ReentrantLock可重入锁,即是公平锁也是非公平锁,根据构造方法传入的Boolean值来确定。
相关类

public abstract class Sync extends AbstractQueuedSynchronizerTest {
	abstract void lock();
	final boolean nonfairTryAcquire(int acquires) {...}
	protected final boolean tryRelease(int releases) {...}
}

public class FairSync extends Sync {
	void lock(){...}
	protected final boolean tryAcquire(int acquires) {...}
}
public class NonfairSync extends Sync {
	void lock(){...}
	protected final boolean tryAcquire(int acquires) {...}
}
    public ReenTrantLockTest(boolean fair) {
        sync = fair ? new FairSync() : new NonfairSync();
    }
根据ReentrantLock源码,自已创建一个ReenTrantLockTest类,方便Debug

上面分析过ReentrantLock是基于AQS来实现加锁和解锁的,所以内部会执有一个AQS成员变量,会根据其构造方法来判断是公平还是非公平实现

public class ReenTrantLockTest implements Lock {
	// AQS引用
    final Sync sync;
	public ReenTrantLockTest(boolean fair) {
    	sync = fair ? new FairSync() : new NonfairSync();
	}

	//模板方法的好处就体现出来了,只要执行sync.lock()-->aqs的tryLock;和sync.release(1);就可以加锁和释放锁
	// 开始加锁
    @Override
    public void lock() {
        sync.lock();
    }
    
    //释放锁
    @Override
    public void unlock() {
        sync.release(1);
    }
}

使用

public class MainActivity extends AppCompatActivity{
    private List<Thread> mThreadList = new ArrayList<>();
    private Lock mLockTest = = new ReenTrantLockTest(true);
    
    // 加锁方法
    public void lock(View view) {
	    Thread thread = new Thread(() -> {
	    	//1
	        mLockTest.lock();
	        System.out.println("还会走下去?");
	        try {
	            Thread.sleep(Integer.MAX_VALUE);
	        } catch (InterruptedException e) {
	            mLockTest.unlock();
	        }
	    });
	    mThreadList.add(thread);
	    thread.start();
	}
	// 释放锁方法
    public void release(View view) {
        Thread thread = mThreadList.get(0);
        thread.interrupt();
        mThreadList.remove(thread);
    }
}

源码分析

注释1: mLockTest.lock();这行代码开到
mLockTest.lock();—>ReenTrantLockTest.lock();—>FairSync.lock();
代码如下

public class FairSync extends Sync {
    final void lock() {
    	//这个实现是在AQS里实现的
        acquire(1);
    }
}

public final void acquire(int arg) {
	//试着拿锁,这个是模板方法,实现是在FairSync里面
    boolean isAcquire = tryAcquire(arg);
    // 如果这里返回true 则证明当前线程已经拿到了锁,下面代码不走
    // 如果返回false, 则肯锁已经被其它线程占用了
    if (!isAcquire) {
    	//2 添加到队列
        Node node = addWaiter(Node.EXCLUSIVE);
        //3 开始排除
        boolean b = acquireQueued(node, arg);
        if (b) {
        	//执行线程的interrupt方法
            selfInterrupt();
        }
    }
}

protected final boolean tryAcquire(int acquires) {
    final Thread current = Thread.currentThread();
    //获取state,如果是0则表示拿到了锁
    int c = getState();
    if (c == 0) {
    	// 判断是否有队列
        boolean hasQueuedPredecessors = hasQueuedPredecessors();
        // 没有,进入到里面,第一次进都是false
        if (!hasQueuedPredecessors) {
        	// 通过CAS修改state为acquires
            boolean b = compareAndSetState(0, acquires);
            // 修改成功 则设置当前线程独占,最后返回true
            if (b) {
                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() {
    Node t = tail;
    Node h = head;
    Node s;
    //  h != t 头节点不等于尾节点,如果相等肯定是没有前置节点则直接返回false后续都不要判断
    // (s = h.next) == null 头节点的下一下节点 == null 如果下一个节点有值,这个队列就不为空。
    return h != t && ((s = h.next) == null || s.thread != Thread.currentThread());
}

开始执行第一次加锁



protected final boolean tryAcquire(int acquires) {
	// 第一个线程
    final Thread current = Thread.currentThread();
    // 第一次进来这里state为原始值0
    int c = getState();
    if (c == 0) {
    	//第一次这里肯定返回false上面有分析
        boolean hasQueuedPredecessors = hasQueuedPredecessors();
        if (!hasQueuedPredecessors) {
        	//这里就将state通过CAS设置为了acquires 1
            boolean b = compareAndSetState(0, acquires);
            if (b) {
            	// 修改成功,设置exclusiveOwnerThread为当前线程 并返回true
                setExclusiveOwnerThread(current);
                return true;
            }
        }
        // current == getExclusiveOwnerThread()这二个肯定不一样
    } else if (current == getExclusiveOwnerThread()) {
        int nextc = c + acquires;
        if (nextc < 0)
            throw new Error("Maximum lock count exceeded");
        setState(nextc);
        return true;
    }
    // 直接return false
    return false;
}

第一次获取锁

日志会打印 com.ancely.fyw I/System.out: 还会走下去?

开始执行第二次lock()



protected final boolean tryAcquire(int acquires) {
	// 第二个线程 
    final Thread current = Thread.currentThread();
    // 这里获取state 为1,
    int c = getState();
    if (c == 0) {
        boolean hasQueuedPredecessors = hasQueuedPredecessors();
        if (!hasQueuedPredecessors) {
            boolean b = compareAndSetState(0, acquires);
            if (b) {
                setExclusiveOwnerThread(current);
                return true;
            }
        }
        // current == getExclusiveOwnerThread()这二个肯定不一样
    } else if (current == getExclusiveOwnerThread()) {
        int nextc = c + acquires;
        if (nextc < 0)
            throw new Error("Maximum lock count exceeded");
        setState(nextc);
        return true;
    }
    // 直接return false
    return false;
}

第二次获取锁



public final void acquire(int arg) {
    boolean isAcquire = tryAcquire(arg);// 上图分析了这个返回的是false
    if (!isAcquire) {
    	//  这次则直接进来这里 创建并添加节点,得到的是创建的节点
        Node node = addWaiter(Node.EXCLUSIVE);
        boolean b = acquireQueued(node, arg);
        if (b) {
            selfInterrupt();
        }
    }
}

在这里插入图片描述



private Node addWaiter(Node mode) {
	// 这里是新创建的节点Node hashCode为12877
    Node node = new Node(mode);
    // 无限遍历
    for (; ; ) {
        Node oldTail = tail;
        // 此时进来的时候tail还没有附值,为null
        if (oldTail != null) {
            ReflectUtils.putObject(node, Node.PREV, oldTail);
            if (compareAndSetTail(oldTail, node)) {
                oldTail.next = node;
                return node;
            }
        } else {
        	// 则直接初始化队列
            initializeSyncQueue();
        }
    }
}

在这里插入图片描述



private void initializeSyncQueue() {
    Node h;
    // h = new Node() 创建了一个h h的hashCode为12878
    // 通过compareAndSwapObject将Sync的head头节点设置为h (12878)
    if (ReflectUtils.compareAndSwapObject(this, HEAD, null, (h = new Node())))
        tail = h; // 设置成功,将tail也附值为h
    // 执行到这一步 二个虚拟节点head 和 tail 都指向的是h (12878)
}

在这里插入图片描述



for (; ; ) {// 接着addWaiter里的无限循环
    Node oldTail = tail; // 此时tail已经有值了12878
    if (oldTail != null) { // 不为null 则直接来到if里面
    	// 通过putObject方法(里面也是CAS原理)将 node(12877) 的前置节点pre 设置为了12878
        ReflectUtils.putObject(node, Node.PREV, oldTail);
        // compareAndSetTail 将尾节点tail 设置为了node(12877)
        if (compareAndSetTail(oldTail, node)) { // 设置成功
        	// 将12878的下一个节点设置成了12877
            oldTail.next = node;
            return node;
        }
    } else {
        initializeSyncQueue();
    }
}
// 最后 head 指向的是12878  tail 指向的是12877  12878的next为12877  12877的pre为12878 双向链表就这样组成了

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

Node node = addWaiter(Node.EXCLUSIVE); 这个node就是12877
boolean b = acquireQueued(node, arg);



final boolean acquireQueued(final Node node, int arg) {
	// node:12877; arg:1;
    try {
        boolean interrupted = false;
        for (; ; ) { //第一次遍历
        	// node的pre为12878
            final Node p = node.predecessor();
            // head此时也是12878  p == head为true  tryAcquire这里就不再分析了 肯定返回false因为第一线程还没有释放锁
            if (p == head && tryAcquire(arg)) {
                setHead(node);
                p.next = null; // help GC
                return interrupted;
            }
            if (shouldParkAfterFailedAcquire(p, node) && parkAndCheckInterrupt())
                interrupted = true;
        }
    } catch (Throwable t) {
        cancelAcquire(node);
        throw t;
    }
}

在这里插入图片描述



private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
	// pred: 12878  node:12877
	// pred的初始值为0  Node.SIGNAL == -1
    int ws = pred.waitStatus;
    // 此时不相等 ws 也小于0
    if (ws == Node.SIGNAL)
        return true;
    if (ws > 0) {
        do {
            node.prev = pred = pred.prev;
        } while (pred.waitStatus > 0);
        pred.next = node;
    } else {
    	// 直接设置pred的waitStatus为Node.SIGNAL
        pred.compareAndSetWaitStatus(ws, Node.SIGNAL);
    }
    return false;
}

在这里插入图片描述



// 第二次循环遍历到这了
private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
	// pred: 12878  node:12877
    int ws = pred.waitStatus;
    // 由于第一次遍历将pre的waitStatus设置为了Node.SIGNAL 所以这里肯定相等
    if (ws == Node.SIGNAL)
    	// 直接返回true
        return true;
    if (ws > 0) {
        do {
            node.prev = pred = pred.prev;
        } while (pred.waitStatus > 0);
        pred.next = node;
    } else {
        pred.compareAndSetWaitStatus(ws, Node.SIGNAL);
    }
    return false;
}

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



private final boolean parkAndCheckInterrupt() {
    LockSupport.park(this);
    return Thread.interrupted();
}

public static void park(Object blocker) {
    Thread t = Thread.currentThread();
    setBlocker(t, blocker);
    // 直接阻塞当前线程
    U.park(false, 0L);
    setBlocker(t, null);
}

在这里插入图片描述
此时第二个线程就一直等待在这了,

释放锁



protected final boolean tryRelease(int releases) {
	// release为1   getState()此时为1 所以c为0
    int c = getState() - releases;
    //释放第一个线程的锁 所以Thread.currentThread()是等于getExclusiveOwnerThread()的
    if (Thread.currentThread() != getExclusiveOwnerThread())
        throw new IllegalMonitorStateException();
    boolean free = false;
    // c=0则时为true
    if (c == 0) {
        free = true;
        // 将exclusiveOwnerThread设置为null
        setExclusiveOwnerThread(null);
    }
    // 设置state的值为0
    setState(c);
    // free为true
    return free;
}

在这里插入图片描述



public final boolean release(int arg) {
	// tryRelease返回true
    if (tryRelease(arg)) {
        Node h = head;
        // head不为null head的waitStatus被设置为了-1   h != null && h.waitStatus != 0这个返回true
        if (h != null && h.waitStatus != 0)
        	//直接来到这
            unparkSuccessor(h);
        // 最后返回的true
        return true;
    }
    return false;
}

在这里插入图片描述



private void unparkSuccessor(Node node) {
	// node 为head 12878 head的waitStatus为-1
    int ws = node.waitStatus; // ws 得到-1
    if (ws < 0)
    	// 将head的waitStatus的状态设置为0
        node.compareAndSetWaitStatus(ws, 0);
    Node s = node.next; // node(12878)的下一个节点12877 所以s 不为null
    if (s == null || s.waitStatus > 0) {
        s = null;
        for (Node p = tail; p != node && p != null; p = p.prev)
            if (p.waitStatus <= 0)
                s = p;
    }
    if (s != null)
    	// 解除s线程的阻塞状态
        LockSupport.unpark(s.thread);
}

在这里插入图片描述



// 此时第二个线程这里就通了 
private final boolean parkAndCheckInterrupt() {
    LockSupport.park(this);
    // 继续执行下面代码
    return Thread.interrupted();
}

在这里插入图片描述



// 这时继续执行第二个线程的这个方法里的for()循环
final boolean acquireQueued(final Node node, int arg) {
    try {
        boolean interrupted = false;
        for (; ; ) { // 直接来到这里继续遍历
            final Node p = node.predecessor();
            // 这里tryAcquire就返回为true了  p == head && tryAcquire(arg) 这个返回true
            if (p == head && tryAcquire(arg)) {
            	// 设置head节点为 node(12877)
                setHead(node);
                p.next = null; // help GC
                return interrupted;
            }
            if (shouldParkAfterFailedAcquire(p, node) && parkAndCheckInterrupt())
                interrupted = true;
        }
    } catch (Throwable t) {
        cancelAcquire(node);
        throw t;
    }
}

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



// 最后来到开始执行的acquire方法的boolean b = acquireQueued(node, arg);下面的逻辑
public final void acquire(int arg) {
    
    if (!isAcquire) {
        Node node = addWaiter(Node.EXCLUSIVE);
        boolean b = acquireQueued(node, arg);
        // 来到这里了 如果b为false则代表已经执行过了Thread的interrupt()
        if (b) {
        	// 如果没有执行则执行一次Thread的interrupt()
            selfInterrupt();
        }
    }
}

最后第二个线程就会打印日志了
在这里插入图片描述
在这里插入图片描述

几个类的源码附上

public class AbstractQueuedSynchronizerTest extends AbstractOwnableSynchronizer implements java.io.Serializable {
    private transient volatile Node head;
    private transient volatile Node tail;
    private volatile int state;

    private static final long STATE;
    private static final long HEAD;
    private static final long TAIL;

    protected boolean tryAcquire(int arg) {
        throw new UnsupportedOperationException();
    }

    protected final void setState(int newState) {
        state = newState;
    }

    protected final int getState() {
        return state;
    }

    protected boolean tryRelease(int arg) {
        throw new UnsupportedOperationException();
    }

    protected final boolean compareAndSetState(int expect, int update) {
        return ReflectUtils.compareAndSwapInt(this, STATE, expect, update);
    }

    public final void acquireInterruptibly(int arg)
            throws InterruptedException {
        if (Thread.interrupted())
            throw new InterruptedException();
        if (!tryAcquire(arg))
            doAcquireInterruptibly(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;
    }

    private void doAcquireInterruptibly(int arg)
            throws InterruptedException {
        final Node node = addWaiter(Node.EXCLUSIVE);
        try {
            for (; ; ) {
                final Node p = node.predecessor();
                if (p == head && tryAcquire(arg)) {
                    setHead(node);
                    p.next = null; // help GC
                    return;
                }
                if (shouldParkAfterFailedAcquire(p, node) &&
                        parkAndCheckInterrupt())
                    throw new InterruptedException();
            }
        } catch (Throwable t) {
            cancelAcquire(node);
            throw t;
        }
    }

    public final boolean hasQueuedPredecessors() {
        Node t = tail;
        Node h = head;
        Node s;
        return h != t && ((s = h.next) == null || s.thread != Thread.currentThread());
    }

    protected int tryAcquireShared(int arg) {
        throw new UnsupportedOperationException();
    }

    protected boolean tryReleaseShared(int arg) {
        throw new UnsupportedOperationException();
    }


    protected boolean isHeldExclusively() {
        throw new UnsupportedOperationException();
    }

    public final void acquire(int arg) {
        boolean isAcquire = tryAcquire(arg);
        if (!isAcquire) {
            Node node = addWaiter(Node.EXCLUSIVE);
            boolean b = acquireQueued(node, arg);
            if (b) {
                selfInterrupt();
            }
        }
    }

    static void selfInterrupt() {
        Thread.currentThread().interrupt();
    }

    final boolean acquireQueued(final Node node, int arg) {
        try {
            boolean interrupted = false;
            for (; ; ) {
                final Node p = node.predecessor();
                if (p == head && tryAcquire(arg)) {
                    setHead(node);
                    p.next = null; // help GC
                    return interrupted;
                }
                if (shouldParkAfterFailedAcquire(p, node) && parkAndCheckInterrupt())
                    interrupted = true;
            }
        } catch (Throwable t) {
            cancelAcquire(node);
            throw t;
        }
    }

    private void cancelAcquire(Node node) {
        if (node == null)
            return;

        node.thread = null;

        Node pred = node.prev;
        while (pred.waitStatus > 0)
            node.prev = pred = pred.prev;

        Node predNext = pred.next;
        node.waitStatus = Node.CANCELLED;

        if (node == tail && compareAndSetTail(node, pred)) {
            pred.compareAndSetNext(predNext, null);
        } else {
            int ws;
            if (pred != head &&
                    ((ws = pred.waitStatus) == Node.SIGNAL ||
                            (ws <= 0 && pred.compareAndSetWaitStatus(ws, Node.SIGNAL))) &&
                    pred.thread != null) {
                Node next = node.next;
                if (next != null && next.waitStatus <= 0)
                    pred.compareAndSetNext(predNext, next);
            } else {
                unparkSuccessor(node);
            }

            node.next = node; // help GC
        }
    }

    private void unparkSuccessor(Node node) {

        int ws = node.waitStatus;
        if (ws < 0)
            node.compareAndSetWaitStatus(ws, 0);

        Node s = node.next;
        if (s == null || s.waitStatus > 0) {
            s = null;
            for (Node p = tail; p != node && p != null; p = p.prev)
                if (p.waitStatus <= 0)
                    s = p;
        }
        if (s != null)
            LockSupport.unpark(s.thread);
    }

    private final boolean parkAndCheckInterrupt() {
        LockSupport.park(this);
        return Thread.interrupted();
    }

    private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
        int ws = pred.waitStatus;
        if (ws == Node.SIGNAL)
            return true;
        if (ws > 0) {
            do {
                node.prev = pred = pred.prev;
            } while (pred.waitStatus > 0);
            pred.next = node;
        } else {
            pred.compareAndSetWaitStatus(ws, Node.SIGNAL);
        }
        return false;
    }

    private Node addWaiter(Node mode) {
        Node node = new Node(mode);

        for (; ; ) {
            Node oldTail = tail;
            if (oldTail != null) {
                ReflectUtils.putObject(node, Node.PREV, oldTail);
                if (compareAndSetTail(oldTail, node)) {
                    oldTail.next = node;
                    return node;
                }
            } else {
                initializeSyncQueue();
            }
        }
    }

    private void initializeSyncQueue() {
        Node h;
        if (ReflectUtils.compareAndSwapObject(this, HEAD, null, (h = new Node())))
            tail = h;
    }

    private void setHead(Node node) {
        head = node;
        node.thread = null;
        node.prev = null;
    }

    private boolean compareAndSetTail(Node expect, Node update) {
        return ReflectUtils.compareAndSwapObject(this, TAIL, expect, update);
    }


    static {
        try {
            STATE = ReflectUtils.objectFieldOffset(AbstractQueuedSynchronizerTest.class.getDeclaredField("state"));
            HEAD = ReflectUtils.objectFieldOffset(AbstractQueuedSynchronizerTest.class.getDeclaredField("head"));
            TAIL = ReflectUtils.objectFieldOffset(AbstractQueuedSynchronizerTest.class.getDeclaredField("tail"));
        } catch (ReflectiveOperationException e) {
            throw new Error(e);
        }

        Class<?> ensureLoaded = LockSupport.class;
    }

    static final class Node {
        static final Node SHARED = new Node();
        static final Node EXCLUSIVE = null;
        static final int CANCELLED = 1;
        static final int SIGNAL = -1;
        static final int CONDITION = -2;

        static final int PROPAGATE = -3;

        volatile int waitStatus;

        volatile Node prev;

        volatile Node next;

        volatile Thread thread;

        Node nextWaiter;

        final boolean isShared() {
            return nextWaiter == SHARED;
        }

        final Node predecessor() throws NullPointerException {
            Node p = prev;
            if (p == null)
                throw new NullPointerException();
            else
                return p;
        }

        Node() {
        }

        Node(Node nextWaiter) {
            this.nextWaiter = nextWaiter;
            ReflectUtils.putObject(this, THREAD, Thread.currentThread());
        }

        private static final long NEXT;
        static final long PREV;
        private static final long THREAD;
        private static final long WAITSTATUS;

        static {
            try {
                NEXT = ReflectUtils.objectFieldOffset(Node.class.getDeclaredField("next"));
                PREV = ReflectUtils.objectFieldOffset(Node.class.getDeclaredField("prev"));
                THREAD = ReflectUtils.objectFieldOffset(Node.class.getDeclaredField("thread"));
                WAITSTATUS = ReflectUtils.objectFieldOffset(Node.class.getDeclaredField("waitStatus"));
            } catch (ReflectiveOperationException e) {
                throw new Error(e);
            }
        }

        final boolean compareAndSetWaitStatus(int expect, int update) {
            return ReflectUtils.compareAndSwapInt(this, Node.WAITSTATUS, expect, update);
        }

        /**
         * CASes next field.
         */
        final boolean compareAndSetNext(Node expect, Node update) {
            return ReflectUtils.compareAndSwapObject(this, NEXT, expect, update);
        }
    }
}

public class FairSync extends Sync {

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

    protected final boolean tryAcquire(int acquires) {
        final Thread current = Thread.currentThread();
        int c = getState();
        if (c == 0) {
            boolean hasQueuedPredecessors = hasQueuedPredecessors();
            if (!hasQueuedPredecessors) {
                boolean b = compareAndSetState(0, acquires);
                if (b) {
                    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 class NonfairSync extends Sync {
    private static final long serialVersionUID = 7316153563782823691L;

    final void lock() {
        if (compareAndSetState(0, 1))
            setExclusiveOwnerThread(Thread.currentThread());
        else
            acquire(1);
    }

    protected final boolean tryAcquire(int acquires) {
        return nonfairTryAcquire(acquires);
    }
}
public class ReenTrantLockTest implements Lock {
    final Sync sync;

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

    @Override
    public void lock() {
        sync.lock();
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {
        sync.acquireInterruptibly(1);
    }

    @Override
    public boolean tryLock() {
        return sync.nonfairTryAcquire(1);
    }


    @Override
    public void unlock() {
        sync.release(1);
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return false;
    }

    @Override
    public Condition newCondition() {
        return null;
    }
}
public class ReflectUtils {
    public static Object mUnsafe = null;
    private static Class<?> sUnsafeClass = null;

    static {
        try {
            sUnsafeClass = Class.forName("sun.misc.Unsafe");
            Method getUnsafeMethod = sUnsafeClass.getMethod("getUnsafe");
            getUnsafeMethod.setAccessible(true);
            mUnsafe = getUnsafeMethod.invoke(null);
        } catch (Exception e) {

        }
    }


    public static long objectFieldOffset(Field field) {
        try {
            Method objectFieldOffset = sUnsafeClass.getDeclaredMethod("objectFieldOffset", Field.class);
            return (long) objectFieldOffset.invoke(mUnsafe, field);
        } catch (Exception e) {
        }
        return 0;
    }

    public static void putObject(Object node, long thread, Object currentThread) {
        try {
            Method putObjectMethod = sUnsafeClass.getDeclaredMethod("putObject", Object.class, long.class, Object.class);
            putObjectMethod.invoke(mUnsafe, node, thread, currentThread);
        } catch (Exception e) {
        }
    }

    public static boolean compareAndSwapObject(Object var1, long var2, Object var4, Object var5) {
        try {
            Method compareAndSwapObjectMethod = sUnsafeClass.getDeclaredMethod("compareAndSwapObject", Object.class, long.class, Object.class, Object.class);
            Object invoke = compareAndSwapObjectMethod.invoke(mUnsafe, var1, var2, var4, var5);
            return (boolean) invoke;
        } catch (Exception e) {
        }
        return false;
    }

    public static boolean compareAndSwapInt(Object var1, long var2, int var4, int var5) {
        try {
            Method compareAndSwapIntMethod = sUnsafeClass.getDeclaredMethod("compareAndSwapInt", Object.class, long.class, int.class, int.class);
            Object invoke = compareAndSwapIntMethod.invoke(mUnsafe, var1, var2, var4, var5);
            return (boolean) invoke;
        } catch (Exception e) {
        }
        return false;
    }
}
public abstract class Sync extends AbstractQueuedSynchronizerTest {
    abstract void lock();

    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;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值