View Javadoc
1   /**
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2015, QOS.ch. All rights reserved.
4    *
5    * This program and the accompanying materials are dual-licensed under
6    * either the terms of the Eclipse Public License v1.0 as published by
7    * the Eclipse Foundation
8    *
9    *   or (per the licensee's choosing)
10   *
11   * under the terms of the GNU Lesser General Public License version 2.1
12   * as published by the Free Software Foundation.
13   */
14  package ch.qos.logback.core.util;
15  
16  import java.util.concurrent.ExecutorService;
17  import java.util.concurrent.Executors;
18  import java.util.concurrent.ScheduledExecutorService;
19  import java.util.concurrent.ScheduledThreadPoolExecutor;
20  import java.util.concurrent.SynchronousQueue;
21  import java.util.concurrent.ThreadFactory;
22  import java.util.concurrent.ThreadPoolExecutor;
23  import java.util.concurrent.TimeUnit;
24  import java.util.concurrent.atomic.AtomicInteger;
25  
26  import ch.qos.logback.core.CoreConstants;
27  
28  /**
29   * Static utility methods for manipulating an {@link ExecutorService}.
30   * 
31   * @author Carl Harris
32   * @author Mikhail Mazursky
33   */
34  public class ExecutorServiceUtil {
35  
36      private static final ThreadFactory THREAD_FACTORY = new ThreadFactory() {
37  
38          private final ThreadFactory defaultFactory = Executors.defaultThreadFactory();
39          private final AtomicInteger threadNumber = new AtomicInteger(1);
40  
41          public Thread newThread(Runnable r) {
42              Thread thread = defaultFactory.newThread(r);
43              if (!thread.isDaemon()) {
44                  thread.setDaemon(true);
45              }
46              thread.setName("logback-" + threadNumber.getAndIncrement());
47              return thread;
48          }
49      };
50  
51      static public ScheduledExecutorService newScheduledExecutorService() {
52          return new ScheduledThreadPoolExecutor(CoreConstants.SCHEDULED_EXECUTOR_POOL_SIZE, THREAD_FACTORY);
53      }
54  
55  
56      /**
57       * Creates an executor service suitable for use by logback components.
58       * @return executor service
59       */
60      static public ExecutorService newExecutorService() {
61          return new ThreadPoolExecutor(CoreConstants.CORE_POOL_SIZE, CoreConstants.MAX_POOL_SIZE, 0L, TimeUnit.MILLISECONDS, new SynchronousQueue<Runnable>(),
62                          THREAD_FACTORY);
63      }
64  
65      /**
66       * Shuts down an executor service.
67       * <p>
68       * @param executorService the executor service to shut down
69       */
70      static public void shutdown(ExecutorService executorService) {
71          executorService.shutdownNow();
72      }
73  
74  }