001package org.eclipse.aether.util.concurrency; 002 003/* 004 * Licensed to the Apache Software Foundation (ASF) under one 005 * or more contributor license agreements. See the NOTICE file 006 * distributed with this work for additional information 007 * regarding copyright ownership. The ASF licenses this file 008 * to you under the Apache License, Version 2.0 (the 009 * "License"); you may not use this file except in compliance 010 * with the License. You may obtain a copy of the License at 011 * 012 * http://www.apache.org/licenses/LICENSE-2.0 013 * 014 * Unless required by applicable law or agreed to in writing, 015 * software distributed under the License is distributed on an 016 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 017 * KIND, either express or implied. See the License for the 018 * specific language governing permissions and limitations 019 * under the License. 020 */ 021 022import java.util.concurrent.Executors; 023import java.util.concurrent.ThreadFactory; 024import java.util.concurrent.atomic.AtomicInteger; 025 026/** 027 * A factory to create worker threads with a given name prefix. 028 */ 029public final class WorkerThreadFactory 030 implements ThreadFactory 031{ 032 033 private final ThreadFactory factory; 034 035 private final String namePrefix; 036 037 private final AtomicInteger threadIndex; 038 039 private static final AtomicInteger POOL_INDEX = new AtomicInteger(); 040 041 /** 042 * Creates a new thread factory whose threads will have names using the specified prefix. 043 * 044 * @param namePrefix The prefix for the thread names, may be {@code null} or empty to derive the prefix from the 045 * caller's simple class name. 046 */ 047 public WorkerThreadFactory( String namePrefix ) 048 { 049 this.factory = Executors.defaultThreadFactory(); 050 this.namePrefix = 051 ( ( namePrefix != null && namePrefix.length() > 0 ) ? namePrefix : getCallerSimpleClassName() + '-' ) 052 + POOL_INDEX.getAndIncrement() + '-'; 053 threadIndex = new AtomicInteger(); 054 } 055 056 private static String getCallerSimpleClassName() 057 { 058 StackTraceElement[] stack = new Exception().getStackTrace(); 059 if ( stack == null || stack.length <= 2 ) 060 { 061 return "Worker-"; 062 } 063 String name = stack[2].getClassName(); 064 name = name.substring( name.lastIndexOf( '.' ) + 1 ); 065 return name; 066 } 067 068 public Thread newThread( Runnable r ) 069 { 070 Thread thread = factory.newThread( r ); 071 thread.setName( namePrefix + threadIndex.getAndIncrement() ); 072 thread.setDaemon( true ); 073 return thread; 074 } 075 076}