View Javadoc

1   /*
2    * $Id: NamedThreadFactory.java 21939 2011-05-18 13:32:09Z aperepel $
3    * --------------------------------------------------------------------------------------
4    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
5    *
6    * The software in this package is published under the terms of the CPAL v1.0
7    * license, a copy of which has been included with this distribution in the
8    * LICENSE.txt file.
9    */
10  
11  package org.mule.util.concurrent;
12  
13  import org.mule.util.StringUtils;
14  
15  import java.util.concurrent.atomic.AtomicLong;
16  
17  public class NamedThreadFactory implements java.util.concurrent.ThreadFactory
18  {
19      private final String name;
20      private final AtomicLong counter;
21      private final ClassLoader contextClassLoader;
22  
23      public NamedThreadFactory(String name)
24      {
25          this(name, null);
26      }
27  
28      public NamedThreadFactory(String name, ClassLoader contextClassLoader)
29      {
30          if (StringUtils.isEmpty(name))
31          {
32              throw new IllegalArgumentException("NamedThreadFactory must have a proper name.");
33          }
34  
35          this.name = name;
36          this.contextClassLoader = contextClassLoader;
37          this.counter = new AtomicLong(1);
38      }
39  
40      public Thread newThread(Runnable runnable)
41      {
42          Thread t = new Thread(runnable);
43          configureThread(t);
44          return t;
45      }
46  
47      protected void configureThread(Thread t)
48      {
49          if (contextClassLoader != null)
50          {
51              t.setContextClassLoader(contextClassLoader);
52          }
53          doConfigureThread(t);
54      }
55  
56      protected void doConfigureThread(Thread t)
57      {
58          t.setName(String.format("%s.%02d", name, counter.getAndIncrement()));
59      }
60  
61      public ClassLoader getContextClassLoader()
62      {
63          return contextClassLoader;
64      }
65  
66      public AtomicLong getCounter()
67      {
68          return counter;
69      }
70  
71      public String getName()
72      {
73          return name;
74      }
75  }