Created
April 11, 2015 16:06
-
-
Save adohe-zz/93934aae8c191148a6ee to your computer and use it in GitHub Desktop.
simple about Semaphore usage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class BoundedHashSet<T> { | |
private final Set<T> set; | |
private final Semaphore sem; | |
public BoundedHashSet(int bound) { | |
set = Collections.synchronizedSet(new HashSet<T>()); | |
sem = new Semphore(bound); | |
} | |
public boolean add(T o) throw InterruptedException { | |
sem.acauire(); | |
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment