001 /** 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017 package org.apache.camel.util.concurrent; 018 019 import java.util.concurrent.ExecutorService; 020 import java.util.concurrent.Executors; 021 import java.util.concurrent.ScheduledExecutorService; 022 import java.util.concurrent.ThreadFactory; 023 import java.util.concurrent.atomic.AtomicInteger; 024 025 /** 026 * Helper for {@link java.util.concurrent.ExecutorService} to construct executors using a thread factory that 027 * create thread names with Camel prefix. 028 * 029 * @version $Revision: 777808 $ 030 */ 031 public final class ExecutorServiceHelper { 032 033 private static AtomicInteger threadCounter = new AtomicInteger(); 034 035 private ExecutorServiceHelper() { 036 } 037 038 /** 039 * Creates a new thread name with the given prefix 040 */ 041 public static String getThreadName(String name) { 042 return "Camel thread " + nextThreadCounter() + ": " + name; 043 } 044 045 protected static synchronized int nextThreadCounter() { 046 return threadCounter.getAndIncrement(); 047 } 048 049 public static ScheduledExecutorService newScheduledThreadPool(final int poolSize, final String name, final boolean daemon) { 050 return Executors.newScheduledThreadPool(poolSize, new ThreadFactory() { 051 public Thread newThread(Runnable r) { 052 Thread answer = new Thread(r, getThreadName(name)); 053 answer.setDaemon(daemon); 054 return answer; 055 } 056 }); 057 } 058 059 public static ExecutorService newFixedThreadPool(final int poolSize, final String name, final boolean daemon) { 060 return Executors.newFixedThreadPool(poolSize, new ThreadFactory() { 061 public Thread newThread(Runnable r) { 062 Thread answer = new Thread(r, getThreadName(name)); 063 answer.setDaemon(daemon); 064 return answer; 065 } 066 }); 067 } 068 069 public static ExecutorService newSingleThreadExecutor(final String name, final boolean daemon) { 070 return Executors.newSingleThreadExecutor(new ThreadFactory() { 071 public Thread newThread(Runnable r) { 072 Thread answer = new Thread(r, getThreadName(name)); 073 answer.setDaemon(daemon); 074 return answer; 075 } 076 }); 077 } 078 079 }