-
-
Save cloudzhou/3d0eae4c77b35117071a05e3d2c4f999 to your computer and use it in GitHub Desktop.
BoundedConcurrency
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 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