View Javadoc

1   /*
2    * $Id: NamedThreadFactory.java 19191 2010-08-25 21:05:23Z tcarlson $
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 edu.emory.mathcs.backport.java.util.concurrent.ThreadFactory;
16  import edu.emory.mathcs.backport.java.util.concurrent.atomic.AtomicLong;
17  
18  public class NamedThreadFactory implements ThreadFactory
19  {
20      private final String name;
21      private final AtomicLong counter;
22      private final ClassLoader contextClassLoader;
23  
24      public NamedThreadFactory(String name)
25      {
26          this(name, null);
27      }
28  
29      public NamedThreadFactory(String name, ClassLoader contextClassLoader)
30      {
31          if (StringUtils.isEmpty(name))
32          {
33              throw new IllegalArgumentException("NamedThreadFactory must have a proper name.");
34          }
35  
36          this.name = name;
37          this.contextClassLoader = contextClassLoader;
38          this.counter = new AtomicLong(1);
39      }
40  
41      public Thread newThread(Runnable runnable)
42      {
43          Thread t = new Thread(runnable);
44          configureThread(t);
45          return t;
46      }
47  
48      protected void configureThread(Thread t)
49      {
50          if (contextClassLoader != null)
51          {
52              t.setContextClassLoader(contextClassLoader);
53          }
54          doConfigureThread(t);
55      }
56  
57      protected void doConfigureThread(Thread t)
58      {
59          t.setName(name + '.' + counter.getAndIncrement());
60      }
61  
62      public ClassLoader getContextClassLoader()
63      {
64          return contextClassLoader;
65      }
66  
67      public AtomicLong getCounter()
68      {
69          return counter;
70      }
71  
72      public String getName()
73      {
74          return name;
75      }
76  }