View Javadoc
1   package org.eclipse.aether.util.concurrency;
2   
3   /*
4    * Licensed to the Apache Software Foundation (ASF) under one
5    * or more contributor license agreements.  See the NOTICE file
6    * distributed with this work for additional information
7    * regarding copyright ownership.  The ASF licenses this file
8    * to you under the Apache License, Version 2.0 (the
9    * "License"); you may not use this file except in compliance
10   * with the License.  You may obtain a copy of the License at
11   * 
12   *  http://www.apache.org/licenses/LICENSE-2.0
13   * 
14   * Unless required by applicable law or agreed to in writing,
15   * software distributed under the License is distributed on an
16   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17   * KIND, either express or implied.  See the License for the
18   * specific language governing permissions and limitations
19   * under the License.
20   */
21  
22  import java.util.concurrent.Executors;
23  import java.util.concurrent.ThreadFactory;
24  import java.util.concurrent.atomic.AtomicInteger;
25  
26  /**
27   * A factory to create worker threads with a given name prefix.
28   */
29  public final class WorkerThreadFactory
30      implements ThreadFactory
31  {
32  
33      private final ThreadFactory factory;
34  
35      private final String namePrefix;
36  
37      private final AtomicInteger threadIndex;
38  
39      private static final AtomicInteger POOL_INDEX = new AtomicInteger();
40  
41      /**
42       * Creates a new thread factory whose threads will have names using the specified prefix.
43       * 
44       * @param namePrefix The prefix for the thread names, may be {@code null} or empty to derive the prefix from the
45       *            caller's simple class name.
46       */
47      public WorkerThreadFactory( String namePrefix )
48      {
49          this.factory = Executors.defaultThreadFactory();
50          this.namePrefix =
51              ( ( namePrefix != null && namePrefix.length() > 0 ) ? namePrefix : getCallerSimpleClassName() + '-' )
52                  + POOL_INDEX.getAndIncrement() + '-';
53          threadIndex = new AtomicInteger();
54      }
55  
56      private static String getCallerSimpleClassName()
57      {
58          StackTraceElement[] stack = new Exception().getStackTrace();
59          if ( stack == null || stack.length <= 2 )
60          {
61              return "Worker-";
62          }
63          String name = stack[2].getClassName();
64          name = name.substring( name.lastIndexOf( '.' ) + 1 );
65          return name;
66      }
67  
68      public Thread newThread( Runnable r )
69      {
70          Thread thread = factory.newThread( r );
71          thread.setName( namePrefix + threadIndex.getAndIncrement() );
72          thread.setDaemon( true );
73          return thread;
74      }
75  
76  }