
com.app.common.thread.AsyncCacheBase Maven / Gradle / Ivy
package com.app.common.thread;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import com.app.common.logger.AsyncSlf4jLoggerFactory;
public class AsyncCacheBase {
private ConcurrentHashMap queue;
protected final Logger logger = AsyncSlf4jLoggerFactory.getLogger(getClass());
public Thread thread;
protected boolean isStop = false;
public String className = null;
protected int maxSize = Integer.MAX_VALUE;
public int sleepTime = -1;
public AsyncCacheBase(int maxSize) {
this(true, maxSize);
}
public class ExceptionHandler implements UncaughtExceptionHandler {
public void uncaughtException(Thread t, Throwable e) {
logger.error("An exception has been captured\n");
logger.error("Thread: {}\n", t.getName());
logger.error("Exception: {}: {}\n", e.getClass().getSimpleName(), e.getMessage());
logger.error("Stack Trace: \n");
logger.error("Thread status: {}\n", t.getState());
}
}
public AsyncCacheBase(boolean paramBoolean, int maxSize) {
queue = new ConcurrentHashMap();
this.thread = new Thread(new Runnable() {
public final void run() {
while (!isStop)
try {
synchronized (queue) {
if (queue.size() == 0) {
queue.wait();
}
}
for (Entry entry : queue.entrySet()) {
T obj = entry.getValue();
String key=entry.getKey();
queue.remove(key);
process(obj);
}
if(sleepTime>0) {
Thread.sleep(sleepTime);
}
} catch (InterruptedException e) {
}catch (Exception localException) {
logger.warn("deliver process error", localException);
}
logger.info("{} exit", className);
}
});
this.thread.setUncaughtExceptionHandler(new ExceptionHandler());
if (paramBoolean) {
start();
return;
}
this.isStop = true;
}
public Thread getThread() {
return this.thread;
}
public ConcurrentHashMap getQueue() {
return this.queue;
}
public void start() {
className = this.className != null ? this.className : getClass().getSimpleName();
this.logger.debug("{} start", className);
if (!StringUtils.isEmpty(className))
this.thread.setName(className);
this.isStop = false;
if (!this.thread.isAlive())
this.thread.start();
}
protected void process(T paramT) {
}
public void add(String key,T paramT) {
queue.put(key, paramT);
synchronized (queue) {
queue.notify();
}
}
public void dispose() {
this.isStop = true;
try {
if (this.thread.isAlive()) {
this.thread.interrupt();
}
} catch (Exception e) {
}
logger.info("{} stop", className);
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy