Semaphore

Semaphore.png

Constructor

// 所谓的信号量就是sync的permits,也就是state
public Semaphore(int permits) {
    sync = new NonfairSync(permits);
}

// 并且信号量分公平和非公平模式
public Semaphore(int permits, boolean fair) {
    sync = fair ? new FairSync(permits) : new NonfairSync(permits);
}

tryAcquireShared

FairSync

protected int tryAcquireShared(int acquires) {
    for (;;) {
        // 基于公平原则看有没有到自己
        if (hasQueuedPredecessors())
            return -1;       
        int available = getState();
        // 计算当前所剩的信号量
        int remaining = available - acquires;
        // 如果所剩的信号量不足,那么直接返回还剩多少
        // 如果还有多余的信号量,且成功更新,那么返回最新的信号量
        // 否则信号量还有剩余,但是更新state失败,那么有必要进入自旋模式,进行重试。
        if (remaining < 0 ||
            compareAndSetState(available, remaining))
            return remaining;
    }
}

NonfairSync

final int nonfairTryAcquireShared(int acquires) {
    for (;;) {
        // 跟公平模式的唯一不同是,这里不需要看下一个是否是按顺序来的,其他都一样
        int available = getState();
        int remaining = available - acquires;
        if (remaining < 0 ||
            compareAndSetState(available, remaining))
            return remaining;
    }
}

tryReleaseShared

protected final boolean tryReleaseShared(int releases) {
    for (;;) {
        int current = getState();
        // 归还信号量,所以state需要加总回来
        int next = current + releases;
        if (next < current) // overflow
            throw new Error("Maximum permit count exceeded");
        // CAS成功
        if (compareAndSetState(current, next))
            return true;
    }
}

你可能感兴趣的:(Semaphore)