Skip to content

Instantly share code, notes, and snippets.

@adohe-zz
Created April 11, 2015 16:06
Show Gist options
  • Save adohe-zz/93934aae8c191148a6ee to your computer and use it in GitHub Desktop.
Save adohe-zz/93934aae8c191148a6ee to your computer and use it in GitHub Desktop.
simple about Semaphore usage
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