美文网首页
Semaphore 源码分析 (基于Java 8)

Semaphore 源码分析 (基于Java 8)

作者: 爱吃鱼的KK | 来源:发表于2017-02-08 23:40 被阅读282次
1. Semaphore 定义

Semaphore 主要用于限量控制并发执行代码的工具类, 其内部通过 一个 permit 来进行定义并发执行的数量, 其实可以理解为一个 限制数量的 ReadLock 获取.

Semaphore 主要特点:

  1. Semaphore 方法的实现通过 Sync(AQS的继承类)代理来实现
    2.支持公平与非公平模式, 都是在AQS的子类里面进行, 主要区分在 tryAcquire 里面

先看一个简单的 demo

import org.apache.log4j.Logger;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by xjk on 9/15/16.
 */
public class SemaphoreExample implements Runnable {

    private static Logger logger = Logger.getLogger(SemaphoreExample.class);

    private static final Semaphore semaphore = new Semaphore(3, true); // 初始化 Semaphore, 限流阀值 为3, 并且指定为公平模式
    private static final AtomicInteger counter = new AtomicInteger(0);

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 5; i++) {
            executorService.execute(new SemaphoreExample()); // 执行 permit 的获取,
        }
        executorService.shutdown();
    }

    public void run() {
        while(counter.incrementAndGet() <= 5) { // Semaphore 被循环获取 5次
            try {
                semaphore.acquire();                // 进行 permit 的获取
            } catch (InterruptedException e) {
                logger.info("["+Thread.currentThread().getName()+"] Interrupted in acquire().");
            }
            logger.info("["+Thread.currentThread().getName()+"] semaphore acquired: "+counter.get());
            semaphore.release();
        }
    }
}

执行结果

[2017-02-12 15:27:12,973] INFO  pool-1-thread-2 (SemaphoreExample.java:35) - [pool-1-thread-2] semaphore acquired: 2
[2017-02-12 15:27:12,973] INFO  pool-1-thread-3 (SemaphoreExample.java:35) - [pool-1-thread-3] semaphore acquired: 3
[2017-02-12 15:27:12,973] INFO  pool-1-thread-1 (SemaphoreExample.java:35) - [pool-1-thread-1] semaphore acquired: 2
[2017-02-12 15:27:12,978] INFO  pool-1-thread-5 (SemaphoreExample.java:35) - [pool-1-thread-5] semaphore acquired: 7
[2017-02-12 15:27:12,978] INFO  pool-1-thread-4 (SemaphoreExample.java:35) - [pool-1-thread-4] semaphore acquired: 6

执行步骤:
上面的代码不好直接看出, 但可以这样理解, 有一段代码, 再

2. Semaphore 构造函数

Semaphore 的功能均由内部类 NonfairSync, FairSync 代理来实现

/**
 * 使用非公平版本构件 Semaphore
 */
public KSemaphore(int permits){
    sync = new NonfairSync(permits);
}

/**
 * 指定版本构件 Semaphore
 */
public KSemaphore(int permits, boolean fair){
    sync = fair ? new FairSync(permits) : new NonfairSync(permits);
}
3. Semaphore 内部类 Sync
/**
 * Synchronization implementation for semaphore. Uses AQS state
 * to represent permits. Subclassed into fair and nonfair
 * versions
 */
/** AQS 的子类主要定义获取释放 lock */
abstract static class Sync extends KAbstractQueuedSynchronizer{
    private static final long serialVersionUID = 1192457210091910933L;

    /**
     * 指定 permit 初始化 Semaphore
     */
    Sync(int permits){
        setState(permits);
    }

    /**
     * 返回剩余 permit
     */
    final int getPermits(){
        return getState();
    }

    /**
     * 获取 permit
     */
    final int nonfairTryAcquireShared(int acquires){
        for(;;){
            int available = getState();
            int remaining = available - acquires; // 判断获取 acquires 的剩余 permit 数目
            if(remaining < 0 ||
                    compareAndSetState(available, remaining)){ // cas改变 state
                return remaining;
            }
        }
    }

    /**
     * 释放 lock
     */
    protected final boolean tryReleaseShared(int releases){
        for(;;){
            int current = getState();
            int next = current + releases;
            if(next < current){ // overflow
                throw new Error(" Maximum permit count exceeded");
            }
            if(compareAndSetState(current, next)){  // cas改变 state
                return true;
            }
        }
    }

    final void reducePermits(int reductions){ // 减少 permits
        for(;;){
            int current = getState();
            int next = current - reductions;
            if(next > current){ // underflow
                throw new Error(" Permit count underflow ");
            }
            if(compareAndSetState(current, next)){
                return;
            }
        }
    }

    /** 将 permit 置为 0 */
    final int drainPermits(){
        for(;;){
            int current = getState();
            if(current == 0 || compareAndSetState(current, 0)){
                return current;
            }
        }
    }

}
4. Semaphore 内部类 FairSync, NonfairSync

这两个类均继承 Sync, 两者的区别主要在于在获取时判断是否有线程在 AQS 的 Sync Queue 里面进行等待获取

/**
 * Nonfair version
 */
/** 非公平版本获取 permit */
static final class NonfairSync extends Sync{

    private static final long serialVersionUID = -2694183684443567898L;

    NonfairSync(int permits) {
        super(permits);
    }

    @Override
    protected int tryAcquireShared(int acquires) {
        return nonfairTryAcquireShared(acquires);
    }
}

/**
 * Fair version
 */
/** 公平版本获取 permit */
static final class FairSync extends Sync{

    private static final long serialVersionUID = 3245289457313211085L;

    FairSync(int permits) {
        super(permits);
    }

    /**
     * 公平版本获取 permit 主要看是否由前继节点
     */
    @Override
    protected int tryAcquireShared(int acquires) {
        for(;;){
            if(hasQueuedPredecessors()){ // 1. 判断是否Sync Queue 里面是否有前继节点
                return -1;
            }
            int available = getState();
            int remaining = available - acquires;
            if(remaining < 0 ||
                    compareAndSetState(available, remaining)){ // 2. cas 改变state
                return remaining;
            }
        }
    }
}
5. Semaphore permit 获取方法

下面这些方法主要通过内部类 Sync, FairSync, NonFairSync 来进行实现

/**
 * 调用 acquireSharedInterruptibly 响应中断的方式获取 permit
 */
public void acquire() throws InterruptedException{
    sync.acquireSharedInterruptibly(1);
}


/**
 * 调用 acquireUninterruptibly 非响应中断的方式获取 permit
 */
public void acquireUninterruptibly(){
    sync.acquireShared(1);
}


/**
 * 尝试获取 permit
 */
public boolean tryAcquire(){
    return sync.nonfairTryAcquireShared(1) >= 0;
}


/**
 * 尝试的获取 permit, 支持超时与中断
 */
public boolean tryAcquire(long timeout, TimeUnit unit) throws InterruptedException{
    return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
}

/**
 * 支持中断的获取permit
 */
public void acquire(int permits) throws InterruptedException{
    if(permits < 0){
        throw new IllegalArgumentException();
    }
    sync.acquireSharedInterruptibly(permits);
}


/**
 * 不响应中断的获取 permit
 */
public void acquireUninterruptibly(int permits){
    if(permits < 0) throw new IllegalArgumentException();
    sync.acquireShared(permits);
}


/**
 * 尝试获取 permit
 */
public boolean tryAcquire(int permits){
    if(permits < 0) throw new IllegalArgumentException();
    return sync.nonfairTryAcquireShared(permits) >= 0;
}


/**
 * 尝试 支持超时机制, 支持中断 的获取 permit
 */
public boolean tryAcquire(int permits, long timout, TimeUnit unit) throws InterruptedException{
    if(permits < 0) throw new IllegalArgumentException();
    return sync.tryAcquireSharedNanos(permits, unit.toNanos(timout));
}
6. Semaphore permit 释放方法
/**
 * 释放 permit
 */
public void release(){
    sync.releaseShared(1);
}

/**
 * 释放 permit
 */
public void release(int permits){
    if(permits < 0) throw new IllegalArgumentException();
    sync.releaseShared(permits);
}
7. Semaphore 工具类方法
/**
 * 返回可用的 permit
 */
public int availablePermits(){
    return sync.getPermits();
}


/**
 * 消耗光 permit
 */
public int drainPermits(){
    return sync.drainPermits();
}


/**
 * 减少 reduction 个permit
 */
protected void reducePermits(int reduction){
   if(reduction < 0) throw new IllegalArgumentException();
    sync.reducePermits(reduction);
}


/**
 * 判断是否是公平版本
 */
public boolean isFair(){
    return sync instanceof FairSync;
}


/**
 * 返回 AQS 中 Sync Queue 里面的等待线程
 */
public final boolean hasQueuedThreads(){
    return sync.hasQueuedThreads();
}

/**
 * 返回 AQS 中 Sync Queue 里面的等待线程长度
 */
public final int getQueueLength(){
    return sync.getQueueLength();
}


/**
 * 返回 AQS 中 Sync Queue 里面的等待线程
 */
protected Collection<Thread> getQueueThreads(){
    return sync.getQueuedThreads();
}
8. 总结

Semaphore 通过 AQS中的 state 来进行控制 permit 的获取控制, 其实它就是一个限制数量的 ReadLock; 但要真正理解 Semaphore, 还需要理解 AbstractQueuedSynchronizer

参考
Java 8 源码分析 AbstractQueuedSynchronizer
Java 8 源码分析 ReentrantReadWriteLock
Java多线程之JUC包:Semaphore源码学习笔记

相关文章

网友评论

      本文标题:Semaphore 源码分析 (基于Java 8)

      本文链接:https://www.haomeiwen.com/subject/wtabittx.html