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); } } } }