JAVA Semaphore详解

  Semaphore(信号量):是一种计数器,用来保护一个或者多个共享资源的访问。如果线程要访问一个资源就必须先获得信号量。如果信号量内部计数器大于0,信号量减1,然后允许共享这个资源;否则,如果信号量的计数器等于0,信号量将会把线程置入休眠直至计数器大于0.当信号量使用完时,必须释放。

实例代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
        final Semaphore semaphore = new Semaphore(2);
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < 10; i++) {
            final int index = i;
            executorService.execute(new Runnable() {
                public void run() {
                    try {
                        semaphore.acquire();
                        System.out.println("线程:" + Thread.currentThread().getName() + "获得许可:" + index);
                        TimeUnit.SECONDS.sleep(1);
                        semaphore.release();
                        System.out.println("允许TASK个数:" + semaphore.availablePermits()); 
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
        executorService.shutdown();

  构造方法1:

1
2
3
public Semaphore(int permits) {
    sync = new NonfairSync(permits);
}

  permits 初始许可数,也就是最大访问线程数构造方法2:

1
2
3
public Semaphore(int permits, boolean fair) {
    sync = (fair)? new FairSync(permits) : new NonfairSync(permits);
}

  permits 初始许可数,也就是最大访问线程数

  fair 当设置为false时,创建的信号量为非公平模式;当设置为true时,信号量是公平模式

主要方法:

  • void acquire() :从信号量获取一个许可,如果无可用许可前将一直阻塞等待,
  • void acquire(int permits) :获取指定数目的许可,如果无可用许可前也将会一直阻塞等待
  • boolean tryAcquire():从信号量尝试获取一个许可,如果无可用许可,直接返回false,不会阻塞
  • boolean tryAcquire(int permits): 尝试获取指定数目的许可,如果无可用许可直接返回false
  • boolean tryAcquire(int permits, long timeout, TimeUnit unit): 在指定的时间内尝试从信号量中获取许可,如果在指定的时间内获取成功,返回true,否则返回false
  • void release(): 释放一个许可,别忘了在finally中使用,注意:多次调用该方法,会使信号量的许可数增加,达到动态扩展的效果,如:初始permits为1, 调用了两次release,最大许可会改变为2
  • int availablePermits(): 获取当前信号量可用的许可

JDK 非公平Semaphore实现:

  1.使用一个参数的构造创建Semaphore对象时,会创建一个NonfairSync对象实例,并将state值设为传入的值(permits ),

1
2
3
public Semaphore(int permits) {
    sync = new NonfairSync(permits);
}

  NonfairSync间接的继承了AbstractQueuedSynchronizer实现

1
2
3
4
5
6
7
8
9
10
11
final static class NonfairSync extends Sync {
        private static final long serialVersionUID = -2694183684443567898L;
 
        NonfairSync(int permits) {
            super(permits);
        }
 
        protected int tryAcquireShared(int acquires) {
            return nonfairTryAcquireShared(acquires);
        }
    }
1
2
3
4
5
6
abstract static class Sync extends AbstractQueuedSynchronizer {
    private static final long serialVersionUID = 1192457210091910933L;
 
    Sync(int permits) {
        setState(permits);
    }

  AbstractQueuedSynchronizer 的setState方法

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

 

  2.调用tryAcquire方法时,实际是调用NonfairSync的nonfairTryAcquireShared方法,nonfairTryAcquireShared在父类Sync中实现,

Semaphore# tryAcquire方法:

1
2
3
public boolean tryAcquire() {
    return sync.nonfairTryAcquireShared(1) >= 0;
}


  Sync的nonfairTryAcquireShared方法

1
2
3
4
5
6
7
8
9
final int nonfairTryAcquireShared(int acquires) {
    for (;;) {
        int available = getState();
        int remaining = available - acquires;
        if (remaining < 0 ||
            compareAndSetState(available, remaining))
            return remaining;
    }
}

  nonfairTryAcquireShared 方法通过获取当前的state,以此state减去需要获取信号量的个数,作为剩余个数,如果结果小于0,返回此剩余的个数;如果结果大于等于0,则基于 CAS将state的值设置为剩余个数,当前步骤用到了for循环,所以只有在结果小于0或设置state值成功的情况下才会退出。如果返回的剩余许可个数大于0,tryAcquire方法则返回true;其余返回false。

  AbstractQueuedSynchronizer的compareAndSetState方法,

1
2
3
4
protected final boolean compareAndSetState(int expect, int update) {
    // See below for intrinsics setup to support this
    return unsafe.compareAndSwapInt(this, stateOffset, expect, update);
}


  3.release方法,释放一个许可

1
2
3
public void release() {
    sync.releaseShared(1);
}

  AbstractQueuedSynchronizer的releaseShared方法,

1
2
3
4
5
6
7
public final boolean releaseShared(int arg) {
    if (tryReleaseShared(arg)) {
        doReleaseShared();
        return true;
    }
    return false;
}

  release方法间接的调用了Sync的tryReleaseShared方法,该方法基于Cas 将state的值设置为state+1,一直循环确保CAS操作成功,成功后返回true。

1
2
3
4
5
6
7
protected final boolean tryReleaseShared(int releases) {
    for (;;) {
        int p = getState();
        if (compareAndSetState(p, p + releases))
            return true;
    }
}

  根据上面分析,可以看得出,Semaphore采用了CAS来实现,尽量避免锁的使用,提高了性能

posted @ 2016-04-22 19:26  简单爱_wxg  阅读(20868)  评论(0编辑  收藏  举报