com.app.common.thread.AsyncSeqThreadGroup Maven / Gradle / Ivy
The newest version!
package com.app.common.thread;
import java.util.ArrayList;
import java.util.List;
import com.app.common.logger.AsyncSlf4jLoggerFactory;
public class AsyncSeqThreadGroup {
private List> htAsyncBase = new ArrayList>();
public AsyncSeqThreadGroup(int asyncBaseNum) {
for (int i = 0; i < asyncBaseNum; i++) {
AsyncBase asyncBase = new AsyncBase(false, Integer.MAX_VALUE) {
@Override
protected void process(T data) {
try {
AsyncSeqThreadGroup.this.process(data);
} catch (Exception e) {
logger.error("{} process error[{}].", className, e);
}
}
};
asyncBase.className = className + i;
asyncBase.start();
htAsyncBase.add(asyncBase);
}
}
private final org.slf4j.Logger logger = AsyncSlf4jLoggerFactory.getLogger(this.getClass());
protected void process(T paramT) {
logger.debug("{} process {}", className, paramT);
}
protected String className = this.getClass().getSimpleName();
public void add(String id, T paramT) {
logger.debug("{} add {} {} begin", className, id, paramT);
int index = Math.abs((id+"").hashCode()) % htAsyncBase.size();
logger.debug("{} add {} threadNum:{} ", className, id, index);
AsyncBase asyncBase = htAsyncBase.get(index);
if (asyncBase != null) {
if (!asyncBase.getThread().isAlive()) {
htAsyncBase.remove(index);
logger.debug("{} add {} threadNum:{} remove", className, id, index);
add(id, paramT);
} else {
asyncBase.add(paramT);
}
logger.debug("{} threadStatus:{},Queue:{}", className, asyncBase.getThread().isAlive(),
asyncBase.getQueue().size());
if(asyncBase.getQueue().size()>100) {
logger.warn("queue[{}] is critical[size:{}]",className+asyncBase.className,asyncBase.getQueue().size());
}
} else {
logger.error("{} add {} asyncBase is null", className, id);
}
logger.debug("{} add {} {} end", className, id, paramT);
}
public void dispose() {
for (AsyncBase asyncBase : htAsyncBase) {
asyncBase.dispose();
}
}
}