ConcurrencyThrottleSupport
ConcurrencyThrottleSupport
用于限制对特定资源的并发访问的支持类。
设计用作基类,子类在其工作流的适当位置调用beforeAccess()和afterAccess()方法。注意,afterAccess通常应该在finally块中调用!
此支持类的默认并发限制为-1(“无界并发”)。子类可以覆盖此默认值
public static final int UNBOUNDED_CONCURRENCY = -1;
private transient Object monitor = new Object();
private int concurrencyLimit = UNBOUNDED_CONCURRENCY; 默认-1不限制
private int concurrencyCount = 0;
#public boolean isThrottleActive() return (this.concurrencyLimit >= 0);
#protected void beforeAccess() 真正执行业务前的限制,本逻辑的方式是wait阻塞等待signal,阻塞时线程可被interrupted
##若concurrencyLimit==0 -> IllegalStateException;
##若concurrencyLimit>0,循环当concurrencyCount >= concurrencyLimit
##若interrupted是true -> IllegalStateException
##进入 monitor.wait(); , 若monitor.wait被interrupted(本线程被interrupted),设置interrupted=true
##否则concurrencyCount++,执行业务
#protected void afterAccess() 若concurrencyLimit >= 0,执行concurrencyCount--; monitor.notify()
#private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException 因为改类实现了Serializable,因此该方法用于反序列化时被调用,初始化monitor对象
使用例子
try{
concurrencyThrottle.beforeAccess();
业务...
}finally{
concurrencyThrottle.afterAccess();
}