com.aspire.nm.component.commonUtil.flow.packageFlow.FlowControl Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of commonUtil Show documentation
Show all versions of commonUtil Show documentation
commonUtil is a dajiangnan's java utils
package com.aspire.nm.component.commonUtil.flow.packageFlow;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class FlowControl extends Thread{
private final static long LONG_TIME_SEC = 1000;
private final static long LONG_TIME_MINUTE = LONG_TIME_SEC * 60;
private final static long LONG_TIME_HOUR = LONG_TIME_MINUTE * 60;
private final static long LONG_TIME_DAY = LONG_TIME_HOUR * 24;
private Lock lock = new ReentrantLock();
private Condition con = lock.newCondition();
private int remain;
private long sleepTime;
private InvokeFlow invokeFlow;
public enum UNIT{
SECOND,
MINUTE,
HOUR,
DAY
}
public FlowControl(final int maxIn,UNIT unit,InvokeFlow invokeFlow) {
this.invokeFlow = invokeFlow;
remain = maxIn;
if(unit == UNIT.SECOND){
sleepTime = LONG_TIME_SEC;
}
if(unit == UNIT.MINUTE){
sleepTime = LONG_TIME_MINUTE;
}
if(unit == UNIT.HOUR){
sleepTime = LONG_TIME_HOUR;
}
if(unit == UNIT.DAY){
sleepTime = LONG_TIME_DAY;
}
Thread t = new Thread(){
public void run(){
while(true){
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
lock.lock();
remain = maxIn;
con.signal();
lock.unlock();
}
}
};
t.setDaemon(true);
t.start();
}
private void sleepForMaxIn(Flowable flowable)
{
lock.lock();
try{
remain -= flowable.flowTimes();
if(remain < 0){
throw new RuntimeException("not enough invoker times in second");
}
if (remain == 0)
{
try {
con.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}finally{
lock.unlock();
}
}
private void tryForMaxIn(Flowable flowable) throws OverSpeedException
{
lock.lock();
try{
remain -= flowable.flowTimes();
if(remain < 0){
throw new OverSpeedException();
}
}finally{
lock.unlock();
}
}
private int getRemain(){
return remain;
}
public void sleepForInvoke(Flowable flowable){
Flowable flowableInvoke = null;
Flowable flowableLeft = flowable;
while(true){
if(flowableLeft == null) break;
Flowable[] flowables = flowableLeft.splitForRemain(getRemain());
flowableInvoke = flowables[0];
flowableLeft = flowables[1];
invokeFlow.invoke(flowableInvoke);
sleepForMaxIn(flowableInvoke);
}
}
public void tryForInvoke(Flowable flowable) throws OverSpeedException{
tryForMaxIn(flowable);
invokeFlow.invoke(flowable);
}
public static class OverSpeedException extends Exception{
private static final long serialVersionUID = 1L;
public OverSpeedException(){
super();
}
public OverSpeedException(String msg){
super(msg);
}
}
}