All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.app.common.thread.AsyncSingleSeqThreadGroup Maven / Gradle / Ivy

The newest version!
package com.app.common.thread;

import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

import com.app.common.logger.AsyncSlf4jLoggerFactory;

public class AsyncSingleSeqThreadGroup {
	private ConcurrentHashMap> htAsyncBase = new ConcurrentHashMap>();

	
	private AsyncBase getSingleCacheThreadGroup(String id) {
		AsyncBase asyncBase = htAsyncBase.get(id);
		if (asyncBase == null) {
			synchronized (className+ id.intern()) {

				if (asyncBase == null) {
				  asyncBase = new AsyncBase(false, Integer.MAX_VALUE) {
						@Override
						protected void process(T data) {
							try {
								AsyncSingleSeqThreadGroup.this.process(data);
							} catch (Exception e) {
								logger.error("{} process error[{}].", className, e);
							}
						}
					};
					asyncBase.className = className + id;
					asyncBase.start();
					 
					htAsyncBase.put(id, asyncBase);
				}
			}

		}
		return 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);
		 
		 AsyncBase asyncBase = getSingleCacheThreadGroup(id);
		if (asyncBase != null) {
			if (!asyncBase.getThread().isAlive()) {
				htAsyncBase.remove(id);
				logger.debug("{} add {} threadNum remove", className, id);
				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 (Entry> entry : htAsyncBase.entrySet()) {
			AsyncBase asyncBase = entry.getValue();
			asyncBase.dispose();
		}
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy