1 16 package com.ibatis.common.util; 17 18 import com.ibatis.common.exception.NestedRuntimeException; 19 20 23 public class Throttle { 24 25 private final Object LOCK = new Object (); 26 27 private int count; 28 private int limit; 29 private long maxWait; 30 31 35 public Throttle(int limit) { 36 this.limit = limit; 37 this.maxWait = 0; 38 } 39 40 45 public Throttle(int limit, long maxWait) { 46 this.limit = limit; 47 this.maxWait = maxWait; 48 } 49 50 53 public void increment() { 54 synchronized (LOCK) { 55 if (count >= limit) { 56 if (maxWait > 0) { 57 long waitTime = System.currentTimeMillis(); 58 try { 59 LOCK.wait(maxWait); 60 } catch (InterruptedException e) { 61 } 63 waitTime = System.currentTimeMillis() - waitTime; 64 if (waitTime > maxWait) { 65 throw new NestedRuntimeException("Throttle waited too long (" + waitTime + ") for lock."); 66 } 67 } else { 68 try { 69 LOCK.wait(); 70 } catch (InterruptedException e) { 71 } 73 } 74 } 75 count++; 76 } 77 } 78 79 82 public void decrement() { 83 synchronized (LOCK) { 84 count--; 85 LOCK.notify(); 86 } 87 } 88 } 89 | Popular Tags |