TaskExecuteHelper.java.svn-base 2.13 KB
Newer Older
Kim Gyeongeun committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
package jp.agentec.sinaburocast.helper;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

import jp.agentec.sinaburocast.common.util.PropertyUtil;

import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.seasar.framework.container.annotation.tiger.Component;
import org.seasar.framework.container.annotation.tiger.DestroyMethod;
import org.seasar.framework.container.annotation.tiger.InstanceType;

@Component(instance=InstanceType.SINGLETON)
public class TaskExecuteHelper {
	private final Log logger = LogFactory.getLog(getClass());

	private Map<String, ThreadPoolExecutor> executorMap = new HashMap<String, ThreadPoolExecutor>();
	
	private final String EXECUTOR_PREFIX = "EXECUTOR_POOL_SIZE.";
	
	public TaskExecuteHelper() {
		init();
	}

	public void init() {
		addExecutor();
	}

	/**
	 * Excecutorを追加する。
	 * 
	 */
	private void addExecutor() {
		Map<String, Object> pMap = PropertyUtil.getPropertiesStartWith(EXECUTOR_PREFIX);
		for (Map.Entry<String, Object> entry : pMap.entrySet()) {
			int poolSize = NumberUtils.toInt((String)entry.getValue());
			if (poolSize > 0) {
				ThreadPoolExecutor executor = (ThreadPoolExecutor)Executors.newFixedThreadPool(poolSize);
				String executorName = entry.getKey().substring(EXECUTOR_PREFIX.length());
				logger.info("Add Executor [" + executorName + "] pool size=" + poolSize);
				executorMap.put(executorName, executor);
			}
		}
	}
	
	public void submit(String executorName, Runnable runnable) {
		ThreadPoolExecutor tpe = executorMap.get(executorName);
		if (tpe != null) {
			tpe.execute(runnable);
		}
		else {
			logger.fatal("no such executor [" + executorName + "]");
		}
	}
	
	@DestroyMethod
	public void shutdownAll() {
		Collection<ThreadPoolExecutor> executorCollection = executorMap.values();
		for (ThreadPoolExecutor threadPoolExecutor : executorCollection) {
			try {
				threadPoolExecutor.shutdownNow();
			} catch (Exception e) {
				logger.warn("executor shutdown failed.", e);
			}
		}
	}
	
}