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 */ 017package org.apache.camel.util.concurrent; 018 019import java.util.concurrent.atomic.AtomicLong; 020import java.util.regex.Pattern; 021 022import org.apache.camel.util.StringHelper; 023 024/** 025 * Various helper method for thread naming. 026 */ 027public final class ThreadHelper { 028 public static final String DEFAULT_PATTERN = "Camel Thread ##counter# - #name#"; 029 private static final Pattern INVALID_PATTERN = Pattern.compile(".*#\\w+#.*"); 030 031 private static AtomicLong threadCounter = new AtomicLong(); 032 033 private ThreadHelper() { 034 } 035 036 private static long nextThreadCounter() { 037 return threadCounter.getAndIncrement(); 038 } 039 040 /** 041 * Creates a new thread name with the given pattern 042 * <p/> 043 * See {@link org.apache.camel.spi.ExecutorServiceManager#setThreadNamePattern(String)} for supported patterns. 044 * 045 * @param pattern the pattern 046 * @param name the name 047 * @return the thread name, which is unique 048 */ 049 public static String resolveThreadName(String pattern, String name) { 050 if (pattern == null) { 051 pattern = DEFAULT_PATTERN; 052 } 053 054 // we support #longName# and #name# as name placeholders 055 String longName = name; 056 String shortName = name.contains("?") ? StringHelper.before(name, "?") : name; 057 058 // replace tokens 059 String answer = StringHelper.replaceAll(pattern, "#counter#", "" + nextThreadCounter()); 060 answer = StringHelper.replaceAll(answer, "#longName#", longName); 061 answer = StringHelper.replaceAll(answer, "#name#", shortName); 062 063 // are there any #word# combos left, if so they should be considered invalid tokens 064 if (INVALID_PATTERN.matcher(answer).matches()) { 065 throw new IllegalArgumentException("Pattern is invalid: " + pattern); 066 } 067 068 return answer; 069 } 070 071}