计数信号量用来控制同时访问某个特定资源的操作数或同时执行某个指定操作的数量
A counting semaphore.Conceptually, a semaphore maintains a set of permits. Each acquire blocks if necessary until a permit is available, and then takes it. Each release adds a permit, potentially releasing a blocking acquirer. However, no actual permit objects are used; the Semaphore just keeps a count of the number available and acts accordingly.
从概念上来说,Semaphore中维护了一组许可,许可的数量在构造函数中指定。acquire方法将获取一个可用的许可,如果没有可用的许可,该方法会被阻塞,直到Semaphore中有可用的许可。release方法释放一个许可,如果此时存在阻塞中的acqure方法,将释放一个阻塞中的acquire
事实上,Semaphore中只维护可用请求数量,并不包含实际的请求对象
示例一:数据库连接池
在初始化Semaphore时可以设置其公平性,如果为公平Semaphore,则按照请求时间获得许可,即先发送的请求先获得许可,如果为非公平Semaphore,则先发送的请求未必先获得许可,这有助于提高程序的吞吐量,但是有可能导致某些请求始终获取不到许可(tryAcquire方法不使用公平性设置)
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.concurrent.Semaphore;
public class MyConnPool {
private LinkedList unusedConns =
new LinkedList();
//释放连接时对查找性能要求较高,故使用哈希表
private Map usedConns =
new HashMap();
private final Semaphore available;
public MyConnPool(int size) throws Exception{
StringBuilder builder = new StringBuilder();
builder.append("-----pool-----\n");
available = new Semaphore(size, true);//公平性Semaphore
String url = "jdbc:mysql://ip:port/name?user=user&password=pwd";
for(int i = 0 ; i < size ; i++){
Connection conn = DriverManager.getConnection(url);
unusedConns.add(conn);
builder.append("conn-" + i + ":" + conn.hashCode() + "\n");
}
builder.append("--------------\n");
System.out.print(builder.toString());
}
public Connection getConn() throws InterruptedException{
//获取Semaphore中的许可
available.acquire();
Connection conn = null;
synchronized(this){
conn = unusedConns.removeFirst();
usedConns.put(conn, "");
System.out.println(Thread.currentThread().getName()
+ ":" + conn.hashCode() + "[got]");
System.out.println(display());
}
return conn;
}
public void close(Connection conn){
synchronized(this){
if(usedConns.containsKey(conn)){
usedConns.remove(conn);
unusedConns.addLast(conn);
System.out.println(Thread.currentThread().getName()
+ ":" + conn.hashCode() + "[closed]");
System.out.println(display());
}
}
//释放线程获取的许可
available.release();
}
private final synchronized String display(){
String str = "";
if(unusedConns.size() > 0){
str = "";
for(Connection conn : unusedConns){
str += conn.hashCode() + "|";
}
}
if(!str.equals(""))
return str;
else
return "empty";
}
}
import java.sql.Connection;
import java.util.concurrent.CountDownLatch;
public class Test implements Runnable{
private static CountDownLatch latch
= new CountDownLatch(1);
private MyConnPool pool;
public Test(MyConnPool pool){
this.pool = pool;
}
@Override
public void run(){
try {
latch.await();
Connection conn = pool.getConn();
Thread.sleep(1*1000);
pool.close(conn);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception{
MyConnPool pool = new MyConnPool(2);
for(int i = 0 ; i < 4 ; i++){
Thread t = new Thread(new Test(pool));
t.start();
}
//保证4个线程同时运行
latch.countDown();
}
}
运行结果如下:
-----pool-----
conn-0:11631043
conn-1:14872264
--------------
Thread-4:11631043[got]
14872264|
Thread-1:14872264[got]
empty
Thread-4:11631043[closed]
11631043|
Thread-2:11631043[got]
empty
Thread-1:14872264[closed]
14872264|
Thread-3:14872264[got]
empty
Thread-2:11631043[closed]
11631043|
Thread-3:14872264[closed]
11631043|14872264|
特别注意如果getConn方法和close方法都为同步方法,将产生死锁:
public synchronized Connection getConn() throws InterruptedException{
......
}
public synchronized void close(Connection conn){
......
}
同一时刻只能有一个线程调用连接池的getConn方法或close方法,当Semaphore中没有可用的许可,并且此时恰好有一个线程成功调用连接池的getConn方法,则该线程将一直阻塞在acquire方法上,其它线程将没有办法获取连接池上的锁并调用close方法释放许可,程序将会卡死
阻塞方法上不要加锁,否则将导致锁长时间不释放,如果该锁为互斥锁,将导致程序卡住
acquire方法本身使用乐观锁实现,也不需要再加互斥锁
示例二:不可重入互斥锁
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;
public class Test implements Runnable{
private static CountDownLatch latch =
new CountDownLatch(1);
private static Semaphore lock =
new Semaphore(1, true);
@Override
public void run(){
try {
latch.await();
this.work();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void work() throws InterruptedException{
lock.acquire();
System.out.println("Locking by "
+ Thread.currentThread().getName());
Thread.sleep(1*1000);
lock.release();
}
public static void main(String[] args) throws Exception{
for(int i = 0 ; i < 4 ; i++){
Thread t = new Thread(new Test());
t.start();
}
//保证4个线程同时运行
latch.countDown();
}
}
运行结果如下:
Locking by Thread-3
Locking by Thread-0
Locking by Thread-1
Locking by Thread-2