Skip to content

Instantly share code, notes, and snippets.

@cloudzhou
Created February 17, 2023 09:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cloudzhou/3d0eae4c77b35117071a05e3d2c4f999 to your computer and use it in GitHub Desktop.
Save cloudzhou/3d0eae4c77b35117071a05e3d2c4f999 to your computer and use it in GitHub Desktop.
BoundedConcurrency
public class BoundedConcurrency {
// https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/Condition.html
private final Lock lock = new ReentrantLock();
private final Condition notFull = lock.newCondition();
private final Condition notEmpty = lock.newCondition();
private int count;
private int max;
public BoundedConcurrency(int max) {
this.max = max;
}
public int getCount() {
lock.lock();
try {
return count;
} finally {
lock.unlock();
}
}
public int getMax() {
lock.lock();
try {
return max;
} finally {
lock.unlock();
}
}
public void incr() {
this.incr(1, TimeUnit.HOURS);
}
public void incr(long time, TimeUnit unit) {
if (this.max == 0) {
return;
}
lock.lock();
try {
while (count >= max) {
try {
notFull.await(time, unit);
} catch (InterruptedException e) {
}
}
count++;
notEmpty.signal();
} finally {
lock.unlock();
}
return;
}
public void decr() {
if (this.max == 0) {
return;
}
lock.lock();
try {
while (count <= 0) {
try {
notEmpty.await();
} catch (InterruptedException e) {
continue;
}
}
count--;
notFull.signal();
} finally {
lock.unlock();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment