new Cached Thread Pool - Java java.util.concurrent

Java examples for java.util.concurrent:ThreadPoolExecutor

Description

new Cached Thread Pool

Demo Code


import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Hashtable;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.log4j.Logger;
import org.apache.log4j.MDC;

public class Main{
    public static final String GROUP_KEY = "GROUP_KEY";
    public static final String EXECUTE_ID_KEY = "EXECUTE_ID_KEY";
    //from  w  w w .ja  va 2s  .com
    public static ExecutorService newCachedThreadPool(int corePoolSize,
            int maxPoolSize, int capacity, int aliveTime, String group,
            final String prefix) {
        if (StringUtils.isEmpty(group))
            group = "sys";
        final String gp = group;
        BlockingQueue<Runnable> bq = null;
        if (capacity == 0)
            bq = new SynchronousQueue<Runnable>();
        else
            bq = new LinkedBlockingQueue<Runnable>(capacity);
        return new ThreadPoolExecutor(corePoolSize, maxPoolSize, aliveTime,
                TimeUnit.SECONDS, bq, new NamedThreadFactory(group)) {
            AtomicInteger ai = new AtomicInteger(1);
            SimpleDateFormat f = new SimpleDateFormat("yyyyMMdd_HHmmss");

            protected void beforeExecute(Thread t, Runnable r) {
                // ?group??????????log4j???????
                MDC.put(GROUP_KEY, gp);
                if (prefix != null)
                    MDC.put(EXECUTE_ID_KEY,
                            prefix + "_" + f.format(new Date()) + "_"
                                    + ai.getAndIncrement());
            }

            protected void afterExecute(Runnable r, Throwable t) {
                Hashtable<?, ?> ht = MDC.getContext();
                if (ht != null)
                    ht.clear();
            }
        };
    }
}

Related Tutorials