001/**
002 * Logback: the reliable, generic, fast and flexible logging framework.
003 * Copyright (C) 1999-2015, QOS.ch. All rights reserved.
004 *
005 * This program and the accompanying materials are dual-licensed under
006 * either the terms of the Eclipse Public License v1.0 as published by
007 * the Eclipse Foundation
008 *
009 *   or (per the licensee's choosing)
010 *
011 * under the terms of the GNU Lesser General Public License version 2.1
012 * as published by the Free Software Foundation.
013 */
014package ch.qos.logback.core.util;
015
016import java.util.concurrent.ExecutorService;
017import java.util.concurrent.Executors;
018import java.util.concurrent.ScheduledExecutorService;
019import java.util.concurrent.ScheduledThreadPoolExecutor;
020import java.util.concurrent.SynchronousQueue;
021import java.util.concurrent.ThreadFactory;
022import java.util.concurrent.ThreadPoolExecutor;
023import java.util.concurrent.TimeUnit;
024import java.util.concurrent.atomic.AtomicInteger;
025
026import ch.qos.logback.core.CoreConstants;
027
028/**
029 * Static utility methods for manipulating an {@link ExecutorService}.
030 * 
031 * @author Carl Harris
032 * @author Mikhail Mazursky
033 */
034public class ExecutorServiceUtil {
035
036    private static final ThreadFactory THREAD_FACTORY = new ThreadFactory() {
037
038        private final ThreadFactory defaultFactory = Executors.defaultThreadFactory();
039        private final AtomicInteger threadNumber = new AtomicInteger(1);
040
041        public Thread newThread(Runnable r) {
042            Thread thread = defaultFactory.newThread(r);
043            if (!thread.isDaemon()) {
044                thread.setDaemon(true);
045            }
046            thread.setName("logback-" + threadNumber.getAndIncrement());
047            return thread;
048        }
049    };
050
051    static public ScheduledExecutorService newScheduledExecutorService() {
052        return new ScheduledThreadPoolExecutor(CoreConstants.SCHEDULED_EXECUTOR_POOL_SIZE, THREAD_FACTORY);
053    }
054
055    /**
056     * Creates an executor service suitable for use by logback components.
057     * 
058     * @return executor service
059     */
060    static public ExecutorService newExecutorService() {
061        return new ThreadPoolExecutor(CoreConstants.CORE_POOL_SIZE, CoreConstants.MAX_POOL_SIZE, 0L,
062                TimeUnit.MILLISECONDS, new SynchronousQueue<Runnable>(), THREAD_FACTORY);
063    }
064
065    /**
066     * Shuts down an executor service.
067     * <p>
068     * 
069     * @param executorService the executor service to shut down
070     */
071    static public void shutdown(ExecutorService executorService) {
072        executorService.shutdownNow();
073    }
074
075}