一、前言
关于taobao的tddl-common包(5.1.0)的com.taobao.tddl.common.utils.BooleanMutex自定义安全布尔类型,通过java.util.concurrent.locks.AbstractQueuedSynchronizer抽象类自定义并发安全控制Sync类,详见源码说明。
二、源码说明
package com.taobao.tddl.common.utils;@b@@b@import java.util.concurrent.TimeUnit;@b@import java.util.concurrent.TimeoutException;@b@import java.util.concurrent.locks.AbstractQueuedSynchronizer;@b@@b@public class BooleanMutex@b@{@b@ private Sync sync;@b@@b@ public BooleanMutex()@b@ {@b@ this.sync = new Sync(this, null);@b@ set(Boolean.valueOf(false));@b@ }@b@@b@ public BooleanMutex(Boolean mutex) {@b@ this.sync = new Sync(this, null);@b@ set(mutex);@b@ }@b@@b@ public void get()@b@ throws InterruptedException@b@ {@b@ this.sync.innerGet();@b@ }@b@@b@ public void get(long timeout, TimeUnit unit)@b@ throws InterruptedException, TimeoutException@b@ {@b@ this.sync.innerGet(unit.toNanos(timeout));@b@ }@b@@b@ public void set(Boolean mutex)@b@ {@b@ if (mutex.booleanValue())@b@ this.sync.innerSetTrue(true);@b@ else@b@ this.sync.innerSetFalse(true);@b@ }@b@@b@ public void trySet(Boolean mutex)@b@ {@b@ if (mutex.booleanValue())@b@ this.sync.innerSetTrue(false);@b@ else@b@ this.sync.innerSetFalse(false);@b@ }@b@@b@ public boolean state()@b@ {@b@ return this.sync.innerState();@b@ }@b@@b@ private final class Sync extends AbstractQueuedSynchronizer@b@ {@b@ private static final long serialVersionUID = 2559471934544126329L;@b@ private static final int TRUE = 1;@b@ private static final int FALSE = 2;@b@@b@ private boolean isTrue()@b@ {@b@ return ((state & 0x1) != 0);@b@ }@b@@b@ protected int tryAcquireShared()@b@ {@b@ return ((isTrue(getState())) ? 1 : -1);@b@ }@b@@b@ protected boolean tryReleaseShared()@b@ {@b@ return true;@b@ }@b@@b@ boolean innerState() {@b@ return isTrue(getState());@b@ }@b@@b@ void innerGet() throws InterruptedException {@b@ acquireSharedInterruptibly(0);@b@ }@b@@b@ void innerGet() throws InterruptedException, TimeoutException {@b@ if (!(tryAcquireSharedNanos(0, nanosTimeout))) throw new TimeoutException();@b@ }@b@@b@ void innerSetTrue() {@b@ while (lazySet) {@b@ int s = getState();@b@ if (s == 1)@b@ return;@b@@b@ if (compareAndSetState(s, 1)) {@b@ releaseShared(0);@b@ return;@b@ }@b@ }@b@ }@b@@b@ void innerSetFalse() {@b@ while (lazySet) {@b@ int s = getState();@b@ if (s == 2)@b@ return;@b@@b@ if (compareAndSetState(s, 2))@b@ return;@b@ }@b@ }@b@ }@b@}