Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class ThrottledRegion_ {
- private class ThrottledRegionForKey {
- public AtomicInteger countInside;
- public ConcurrentLinkedQueue<Boolean> waitingQueue ;
- public ReentrantLock _reentrantLock = new ReentrantLock();
- public ThrottledRegionForKey() {
- waitingQueue = new ConcurrentLinkedQueue<Boolean>();
- countInside = new AtomicInteger(0);
- }
- public boolean tryEnter() throws InterruptedException {
- do{
- int countInsideAux = countInside.get();
- if(countInsideAux < maxInside){
- if(countInside.compareAndSet(countInsideAux, countInsideAux+1)){
- return true;
- }
- continue;
- }
- if(waitTimeout == 0){
- return false;
- }
- if (waitingQueue.size() > maxWaiting)
- {
- return false;
- }
- TimeoutHolder th = new TimeoutHolder(waitTimeout);
- Boolean node = new Boolean(false);
- waitingQueue.add(node);
- do{
- if(th.value() == waitTimeout ){
- waitingQueue.remove(node);
- return false;
- }
- try{
- _reentrantLock.wait(waitTimeout);
- }catch(InterruptedException tre){
- waitingQueue.remove(node);
- Thread.currentThread().interrupt();
- throw tre;
- }
- }while(node.booleanValue() == false);
- return true;
- }while(true);
- }
- public void leave() {
- do{
- int countInsideAux = countInside.get();
- if(countInsideAux > 0){
- if(countInside.compareAndSet(countInsideAux, countInsideAux-1)){
- if(waitingQueue.size() > 0){
- Boolean n = waitingQueue.poll();
- n = true;
- _reentrantLock.notifyAll();
- break;
- }
- }
- }else{
- break;
- }
- }while(true);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement