概述
为了提高接口的响应速度,可以使用ThreadPoolExecutor + Runnable 或者ThreadPoolExecutor 并发调用 技术来并行执行task。但是ThreadPoolExecutor有个特点,就是当core线程不足以应付请求的时候,会将task加入到队列中。一旦使用队列,那么就可能出现队列爆掉或者队列导致的内存溢出问题。为了尽快提供接口响应速度,但是又不想使用队列特性的话。可以使用信号量来做到。
Semaphore信号量管理着一组许可,在执行操作时需要首先获得许可,并在使用后释放许可。如果已经没有许可了, acquire方法将一直阻塞,直到有许可。Semaphore可以用来实现有界阻塞容器。
信号量简单例子
这里使用JAVA并发编程一书中的例子来说明信号量的基本用法。
public class BoundedHashSet {
public static void main(String[] args) throws Exception {
BoundedHashSet set = new BoundedHashSet<>(2);
set.add("1");
set.add("2");
set.remove("2");
set.add("3");
System.out.println(JSON.toJSONString(set));
}
private final Set tempSet;
private final Semaphore sem;
public BoundedHashSet(int size) {
this.tempSet = Collections.synchr