1 | |
|
2 | |
|
3 | |
|
4 | |
|
5 | |
|
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 | 0 | this(name, null); |
23 | 0 | } |
24 | |
|
25 | |
public NamedThreadFactory(String name, ClassLoader contextClassLoader) |
26 | 0 | { |
27 | 0 | if (StringUtils.isEmpty(name)) |
28 | |
{ |
29 | 0 | throw new IllegalArgumentException("NamedThreadFactory must have a proper name."); |
30 | |
} |
31 | |
|
32 | 0 | this.name = name; |
33 | 0 | this.contextClassLoader = contextClassLoader; |
34 | 0 | this.counter = new AtomicLong(1); |
35 | 0 | } |
36 | |
|
37 | |
public Thread newThread(Runnable runnable) |
38 | |
{ |
39 | 0 | Thread t = new Thread(runnable); |
40 | 0 | configureThread(t); |
41 | 0 | return t; |
42 | |
} |
43 | |
|
44 | |
protected void configureThread(Thread t) |
45 | |
{ |
46 | 0 | if (contextClassLoader != null) |
47 | |
{ |
48 | 0 | t.setContextClassLoader(contextClassLoader); |
49 | |
} |
50 | 0 | doConfigureThread(t); |
51 | 0 | } |
52 | |
|
53 | |
protected void doConfigureThread(Thread t) |
54 | |
{ |
55 | 0 | t.setName(name + '.' + counter.getAndIncrement()); |
56 | 0 | } |
57 | |
|
58 | |
public ClassLoader getContextClassLoader() |
59 | |
{ |
60 | 0 | return contextClassLoader; |
61 | |
} |
62 | |
|
63 | |
public AtomicLong getCounter() |
64 | |
{ |
65 | 0 | return counter; |
66 | |
} |
67 | |
|
68 | |
public String getName() |
69 | |
{ |
70 | 0 | return name; |
71 | |
} |
72 | |
} |