Java基于Semaphore構(gòu)建阻塞對(duì)象池
java中使用Semaphore構(gòu)建阻塞對(duì)象池
Semaphore是java 5中引入的概念,叫做計(jì)數(shù)信號(hào)量。主要用來控制同時(shí)訪問某個(gè)特定資源的訪問數(shù)量或者執(zhí)行某個(gè)操作的數(shù)量。
Semaphore中定義了一組虛擬的permits,通過獲取和釋放這些permits,Semaphore可以控制資源的個(gè)數(shù)。
Semaphore的這個(gè)特性可以用來構(gòu)造資源池,比如數(shù)據(jù)庫連接池等。
Semaphore有兩個(gè)構(gòu)造函數(shù):
public Semaphore(int permits) { sync = new NonfairSync(permits); } public Semaphore(int permits, boolean fair) { sync = fair ? new FairSync(permits) : new NonfairSync(permits); }
permits定義了許可資源的個(gè)數(shù),而fair則表示是否支持FIFO的順序。
兩個(gè)比較常用的方法就是acquire和release了。
public void acquire() throws InterruptedException { sync.acquireSharedInterruptibly(1); } public void release() { sync.releaseShared(1); }
其中acquire用來獲取資源,release用來釋放資源。
有了這兩個(gè)特性, 我們看一下怎么使用Semaphore來定義一個(gè)一個(gè)有界容器。
我們可以將Semaphore初始化為容器池大小,并且在容器池獲取資源時(shí)調(diào)用acquire,將資源返回給容器池之后再調(diào)用release。
我們看下面的一個(gè)實(shí)現(xiàn):
public class SemaphoreUsage<T> { private final Set<T> set; private final Semaphore sem; public SemaphoreUsage(int bound){ this.set = Collections.synchronizedSet(new HashSet<T>()); sem= new Semaphore(bound); } public boolean add (T o) throws InterruptedException{ sem.acquire(); boolean wasAdded = false; try{ wasAdded=set.add(o); return wasAdded; }finally { if(!wasAdded){sem.release(); } } } public boolean remove(Object o){ boolean wasRemoved = set.remove(o); if(wasRemoved){ sem.release(); } return wasRemoved; }}
上面的例子我們定義了一個(gè)有界的synchronizedSet。 要注意一點(diǎn)是在add方法中,只有add成功之后才會(huì)調(diào)用release方法。
本文的例子請(qǐng)參考https://github.com/ddean2009/learn-java-concurrency/tree/master/Semaphore
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. IntelliJ IDEA設(shè)置默認(rèn)瀏覽器的方法2. idea自定義快捷鍵的方法步驟3. PHP腳本的10個(gè)技巧(8)4. IntelliJ IDEA調(diào)整字體大小的方法5. IntelliJ IDEA導(dǎo)出項(xiàng)目的方法6. python中復(fù)數(shù)的共軛復(fù)數(shù)知識(shí)點(diǎn)總結(jié)7. IntelliJ IDEA設(shè)置背景圖片的方法步驟8. IntelliJ IDEA配置Tomcat服務(wù)器的方法9. Django中如何使用Channels功能10. jsp網(wǎng)頁實(shí)現(xiàn)貪吃蛇小游戲
