View Javadoc

1   /***
2    *  Copyright 2003-2010 Terracotta, Inc.
3    *
4    *  Licensed under the Apache License, Version 2.0 (the "License");
5    *  you may not use this file except in compliance with the License.
6    *  You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   *  Unless required by applicable law or agreed to in writing, software
11   *  distributed under the License is distributed on an "AS IS" BASIS,
12   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   *  See the License for the specific language governing permissions and
14   *  limitations under the License.
15   */
16  
17  package net.sf.ehcache.util;
18  
19  import java.util.concurrent.ThreadFactory;
20  import java.util.concurrent.atomic.AtomicInteger;
21  
22  /***
23   * A {@link ThreadFactory} that sets names to the threads created by this factory. Threads created by this factory
24   * will take names in the form of the string <code>namePrefix + " thread-" + threadNum</code> where <tt>threadNum</tt> is the 
25   * count of threads created by this type of factory.
26   * 
27   * @author <a href="mailto:asanoujam@terracottatech.com">Abhishek Sanoujam</a>
28   * 
29   */
30  public class NamedThreadFactory implements ThreadFactory {
31  
32      private static AtomicInteger threadNumber = new AtomicInteger(1);
33      private final String namePrefix;
34  
35      /***
36       * Constructor accepting the prefix of the threads that will be created by this {@link ThreadFactory}
37       * 
38       * @param namePrefix
39       *            Prefix for names of threads
40       */
41      public NamedThreadFactory(String namePrefix) {
42          this.namePrefix = namePrefix;
43      }
44  
45      /***
46       * Returns a new thread using a name as specified by this factory {@inheritDoc}
47       */
48      public Thread newThread(Runnable runnable) {
49          return new Thread(runnable, namePrefix + " thread-" + threadNumber.getAndIncrement());
50      }
51  
52  }