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