Advertisement
Guest User

Untitled

a guest
Jul 21st, 2017
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.46 KB | None | 0 0
  1. public class ThrottledRegion_ {
  2. private class ThrottledRegionForKey {
  3. public AtomicInteger countInside;
  4. public ConcurrentLinkedQueue<Boolean> waitingQueue ;
  5. public ReentrantLock _reentrantLock = new ReentrantLock();
  6.  
  7. public ThrottledRegionForKey() {
  8. waitingQueue = new ConcurrentLinkedQueue<Boolean>();
  9. countInside = new AtomicInteger(0);
  10. }
  11.  
  12. public boolean tryEnter() throws InterruptedException {
  13. do{
  14. int countInsideAux = countInside.get();
  15. if(countInsideAux < maxInside){
  16. if(countInside.compareAndSet(countInsideAux, countInsideAux+1)){
  17. return true;
  18. }
  19. continue;
  20. }
  21. if(waitTimeout == 0){
  22. return false;
  23. }
  24. if (waitingQueue.size() > maxWaiting)
  25. {
  26. return false;
  27. }
  28. TimeoutHolder th = new TimeoutHolder(waitTimeout);
  29. Boolean node = new Boolean(false);
  30. waitingQueue.add(node);
  31. do{
  32. if(th.value() == waitTimeout ){
  33. waitingQueue.remove(node);
  34. return false;
  35. }
  36. try{
  37. _reentrantLock.wait(waitTimeout);
  38. }catch(InterruptedException tre){
  39. waitingQueue.remove(node);
  40. Thread.currentThread().interrupt();
  41.  
  42. throw tre;
  43. }
  44. }while(node.booleanValue() == false);
  45.  
  46. return true;
  47. }while(true);
  48.  
  49. }
  50.  
  51. public void leave() {
  52. do{
  53. int countInsideAux = countInside.get();
  54. if(countInsideAux > 0){
  55. if(countInside.compareAndSet(countInsideAux, countInsideAux-1)){
  56. if(waitingQueue.size() > 0){
  57. Boolean n = waitingQueue.poll();
  58. n = true;
  59. _reentrantLock.notifyAll();
  60. break;
  61. }
  62. }
  63. }else{
  64. break;
  65. }
  66. }while(true);
  67. }
  68. }
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement