aqs小记
AbstractQueuedSynchronizer是Java中许多同步类的底层实现原理。ReentranLocl、CyclicBarrier、Semaphore、CountdownLatch等都是基于aqs实现的。 这个是一种模板模式的实现。使用的时候一般是先声明一个内部类继承aqs,然后实现tryRelease()和tryRequire()方法(独占锁方式), 或者tryReleaShared()和tryAcquireShared()(共享方式)内部通过getState和setState对aqs的state进行操作,实现同步控制。
一个例子:
/**
* 独占式非共享锁
*/
public class Mutex implements Lock{
@Override
public void lock() {
sync.acquire(1);
}
@Override
public void lockInterruptibly() throws InterruptedException {
sync.acquireInterruptibly(1);
}
@Override
public boolean tryLock() {
return false;
}
@Override
public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
return false;
}
@Override
public void unlock() {
sync.release(1);
}
@Override
public Condition newCondition() {
return null;
}
private final Sync sync = new Sync();
private static class Sync extends AbstractQueuedSynchronizer {
@Override
protected boolean tryAcquire(int arg) {
if (compareAndSetState(0, 1)) {
setExclusiveOwnerThread(Thread.currentThread());
return true;
}
return false;
}
@Override
protected boolean tryRelease(int arg) {
if (getState() == 0 || Thread.currentThread() != getExclusiveOwnerThread()) {
throw new IllegalMonitorStateException();
}
setExclusiveOwnerThread(null);
setState(0);
return true;
}
}
}
Written on October 22, 2018