Semaphore (JDK)

我们使用semaphore去限制获取特定资源的并发线程数量。

下面的例子中,我们实现了一个简单的登录队列来限制登入系统的用户数量:

class LoginQueueUsingSemaphore {

    private Semaphore semaphore;

    public LoginQueueUsingSemaphore(int slotLimit) {
semaphore = new Semaphore(slotLimit);
} boolean tryLogin() {
return semaphore.tryAcquire();
} void logout() {
semaphore.release();
} int availableSlots() {
return semaphore.availablePermits();
}
}

注意下我们使用这些方法的方式:

  • tryAcquire():如果还有可用的permit(构造方法传入的,表示限制的线程数量)则立即返回true,否则返回false,但是acquire()方法会以阻塞的方式获取一个permit。
  • release():释放一个permit。
  • availablePermits():返回当前可用的permit数量。

我们来测试一下我们的登录队列,我们首先使用完所有的permit,然后再获取一个看看是否会被阻塞:

@Test
public void givenLoginQueue_whenReachLimit_thenBlocked() {
int slots = 10;
ExecutorService executorService = Executors.newFixedThreadPool(slots);
LoginQueueUsingSemaphore loginQueue = new LoginQueueUsingSemaphore(slots);
IntStream.range(0, slots)
.forEach(user -> executorService.execute(loginQueue::tryLogin));
executorService.shutdown(); assertEquals(0, loginQueue.availableSlots());
assertFalse(loginQueue.tryLogin());
}

现在我们logout()一下看看是否有可用的permit:

@Test
public void givenLoginQueue_whenLogout_thenSlotsAvailable() {
int slots = 10;
ExecutorService executorService = Executors.newFixedThreadPool(slots);
LoginQueueUsingSemaphore loginQueue = new LoginQueueUsingSemaphore(slots);
IntStream.range(0, slots)
.forEach(user -> executorService.execute(loginQueue::tryLogin));
executorService.shutdown();
assertEquals(0, loginQueue.availableSlots());
loginQueue.logout(); assertTrue(loginQueue.availableSlots() > 0);
assertTrue(loginQueue.tryLogin());
}

结果显而易见。

Timed Semaphore (Apache Commons)

我们现在看看ApacheCommons下实现的TimedSemaphore。TimedSemaphore允许在既定的时间内维护一定数量的Semaphore(这段时间内和JDK实现的Semaphore效果一样),当时间过去后会释放所有的permits。

我们可以使用TimedSemaphore来构建一个简单的延时队列:

class DelayQueueUsingTimedSemaphore {

    private TimedSemaphore semaphore;

    DelayQueueUsingTimedSemaphore(long period, int slotLimit) {
semaphore = new TimedSemaphore(period, TimeUnit.SECONDS, slotLimit);
} boolean tryAdd() {
return semaphore.tryAcquire();
} int availableSlots() {
return semaphore.getAvailablePermits();
}
}

现在我们设置超时时间1秒,在1秒钟之内使用完所有的permit再次尝试获取的时候就会没有可用的permit:

public void givenDelayQueue_whenReachLimit_thenBlocked() {
int slots = 50;
ExecutorService executorService = Executors.newFixedThreadPool(slots);
DelayQueueUsingTimedSemaphore delayQueue
= new DelayQueueUsingTimedSemaphore(1, slots); IntStream.range(0, slots)
.forEach(user -> executorService.execute(delayQueue::tryAdd));
executorService.shutdown(); assertEquals(0, delayQueue.availableSlots());
assertFalse(delayQueue.tryAdd());
}

但是把线程休眠1秒后,这时候semaphore会重置并释放所有的permits

@Test
public void givenDelayQueue_whenTimePass_thenSlotsAvailable() throws InterruptedException {
int slots = 50;
ExecutorService executorService = Executors.newFixedThreadPool(slots);
DelayQueueUsingTimedSemaphore delayQueue = new DelayQueueUsingTimedSemaphore(1, slots);
IntStream.range(0, slots)
.forEach(user -> executorService.execute(delayQueue::tryAdd));
executorService.shutdown(); assertEquals(0, delayQueue.availableSlots());
Thread.sleep(1000);
assertTrue(delayQueue.availableSlots() > 0);
assertTrue(delayQueue.tryAdd());
}

Semaphore vs. Mutex

Mutex像是一个二进制的Semaphore,我们可以使用它来实现互斥。

在下面的这个例子中,我们使用一个permit为1的Semaphore来构建一个计数器:

class CounterUsingMutex {

    private Semaphore mutex;
private int count; CounterUsingMutex() {
mutex = new Semaphore(1);
count = 0;
} void increase() throws InterruptedException {
mutex.acquire();
this.count = this.count + 1;
Thread.sleep(1000);
mutex.release(); } int getCount() {
return this.count;
} boolean hasQueuedThreads() {
return mutex.hasQueuedThreads();
}
}

当大量线程同时来操作counter的时候,他们都会在队列中阻塞:

@Test
public void whenMutexAndMultipleThreads_thenBlocked()
throws InterruptedException {
int count = 5;
ExecutorService executorService
= Executors.newFixedThreadPool(count);
CounterUsingMutex counter = new CounterUsingMutex();
IntStream.range(0, count)
.forEach(user -> executorService.execute(() -> {
try {
counter.increase();
} catch (InterruptedException e) {
e.printStackTrace();
}
}));
executorService.shutdown(); assertTrue(counter.hasQueuedThreads());
}

我们把线程休眠一会后,所有的线程都将能操作counter,这时队列中就没有等待排队的线程了。

@Test
public void givenMutexAndMultipleThreads_ThenDelay_thenCorrectCount()
throws InterruptedException {
int count = 5;
ExecutorService executorService
= Executors.newFixedThreadPool(count);
CounterUsingMutex counter = new CounterUsingMutex();
IntStream.range(0, count)
.forEach(user -> executorService.execute(() -> {
try {
counter.increase();
} catch (InterruptedException e) {
e.printStackTrace();
}
}));
executorService.shutdown(); assertTrue(counter.hasQueuedThreads());
Thread.sleep(5000);
assertFalse(counter.hasQueuedThreads());
assertEquals(count, counter.getCount());
}

CodeRepo

完整代码在这

JUC并发工具包之Semaphore的更多相关文章

  1. java架构之路(多线程)JUC并发编程之Semaphore信号量、CountDownLatch、CyclicBarrier栅栏、Executors线程池

    上期回顾: 上次博客我们主要说了我们juc并发包下面的ReetrantLock的一些简单使用和底层的原理,是如何实现公平锁.非公平锁的.内部的双向链表到底是什么意思,prev和next到底是什么,为什 ...

  2. JUC并发工具包之CyclicBarrier & CountDownLatch的异同

    1.介绍 本文我们将比较一下CyclicBarrier和CountDownLatch并了解两者的相似与不同. 2.两者是什么 当谈到并发,将这两者概念化的去解释两者是做什么的,这其实是一件很有挑战的事 ...

  3. JUC并发工具包之CountDownLatch

    1.介绍 本文将介绍CountDownLatch并给出实践中的几个例子,通过使用CountDownLatch我们可以让一个线程阻塞直到其他一个或多个线程执行完成. A synchronization ...

  4. JUC并发工具包之CyclicBarrier

    1.简介 CyclicBarrier是一个同步器,允许多个线程等待彼此直到达一个执行点(barrier). CyclicBarrier都是在多个线程必须等到彼此都到达同一个执行点后才执行一段逻辑时才被 ...

  5. Java 语言特性【一】——JUC(Java 并发工具包)

    引言 JUC即java.util.concurrent,是java提供的用于多线程处理的工具类库.重点关注 ConcurrentXXX.AtomicXXX.Executor.Caller&&a ...

  6. Java 并发工具包 java.util.concurrent 用户指南

    1. java.util.concurrent - Java 并发工具包 Java 5 添加了一个新的包到 Java 平台,java.util.concurrent 包.这个包包含有一系列能够让 Ja ...

  7. Java并发编程-并发工具包(java.util.concurrent)使用指南(全)

    1. java.util.concurrent - Java 并发工具包 Java 5 添加了一个新的包到 Java 平台,java.util.concurrent 包.这个包包含有一系列能够让 Ja ...

  8. Java 8并发工具包漫游指南

    Java 8并发工具包简介 Java 8并发工具包由3个包组成,分别是java.util.concurrent.java.util.concurrent.atomic和java.util.concur ...

  9. Java_并发工具包 java.util.concurrent 用户指南(转)

    译序 本指南根据 Jakob Jenkov 最新博客翻译,请随时关注博客更新:http://tutorials.jenkov.com/java-util-concurrent/index.html.本 ...

随机推荐

  1. Python ( 学习 基础篇第一部 )

    目录 注释 注释的分类 注释的注意点 变量 变量的概念 变量的声明 变量的命名 变量的交换 变量的缓存机制 常量 进制 进制的转换 原码 反码 补码 六大数据类型 Number 的四大类 字符串 st ...

  2. Vue基础语法(四)

    vue的生命周期钩子函数 所有的生命周期钩子自动绑定this到上下文实例中,因此可以访问数据对property和方法进行运算,这意味着不蹦使用箭头函数来定义一个生命周期方法.参考官方文档,生命周期图 ...

  3. Python&&Pip

    Pip简易使用 使用pip list命令就可以发现自己电脑里所安装库的名字.如图展示的出来的有package.Version.Location三列,package是下载的python库名,Versio ...

  4. Triple的使用

    public Triple<Long, Long, Double> getCarRunSummary(String did, Date startDate, Date endDate) { ...

  5. 【转】not found while looking for property错误

    原址:http://blog.csdn.net/y3wegy/article/details/7840813 最近在研究Hibernate.过程当中碰到了很多问题啊!其中一个就是not found w ...

  6. 深入探究ASP.NET Core Startup初始化

    前言 Startup类相信大家都比较熟悉,在我们使用ASP.NET Core开发过程中经常用到的类,我们通常使用它进行IOC服务注册,配置中间件信息等.虽然它不是必须的,但是将这些操作统一在Start ...

  7. 我的 Redis 被入侵了

    好吧,我也做了回标题党,像我这么细心的同学,怎么可能让服务器被入侵呢? 其实是这样的,昨天我和一个朋友聊天,他说他自己有一台云服务器运行了 Redis 数据库,有一天突然发现数据库里的数据全没了,只剩 ...

  8. K8s之实践Pod深入理解

      K8s之实践Pod深入理解 1.同一pod下的nginx+php+mysql nginx+php+mysql.yaml文件 --- apiVersion: v1 kind: Secret meta ...

  9. 快进来!花几分钟看一下 ReentrantReadWriteLock 的原理!

    前言 在看完 ReentrantLock 之后,在高并发场景下 ReentrantLock 已经足够使用,但是因为 ReentrantLock 是独占锁,同时只有一个线程可以获取该锁,而很多应用场景都 ...

  10. Java入门(4)

    阅读书目:Java入门经典(第7版) 作者:罗格斯·卡登海德 面向对象编程(OOP)将程序视为对象的集合,确定程序要完成的任务,然后将这些任务指派给最适合完成它们的对象.换言之,计算机程序是一组对象, ...