1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.jboss.netty.util;
17
18 import org.jboss.netty.logging.InternalLogger;
19 import org.jboss.netty.logging.InternalLoggerFactory;
20
21
22
23
24
25
26
27
28
29
30 public class ThreadRenamingRunnable implements Runnable {
31
32 private static final InternalLogger logger =
33 InternalLoggerFactory.getInstance(ThreadRenamingRunnable.class);
34
35 private static volatile ThreadNameDeterminer threadNameDeterminer =
36 ThreadNameDeterminer.PROPOSED;
37 private final ThreadNameDeterminer determiner;
38
39
40
41
42
43 public static ThreadNameDeterminer getThreadNameDeterminer() {
44 return threadNameDeterminer;
45 }
46
47
48
49
50
51
52
53
54
55
56
57 public static void setThreadNameDeterminer(ThreadNameDeterminer threadNameDeterminer) {
58 if (threadNameDeterminer == null) {
59 throw new NullPointerException("threadNameDeterminer");
60 }
61 ThreadRenamingRunnable.threadNameDeterminer = threadNameDeterminer;
62 }
63
64 private final Runnable runnable;
65 private final String proposedThreadName;
66
67
68
69
70
71
72 public ThreadRenamingRunnable(Runnable runnable, String proposedThreadName, ThreadNameDeterminer determiner) {
73 if (runnable == null) {
74 throw new NullPointerException("runnable");
75 }
76 if (proposedThreadName == null) {
77 throw new NullPointerException("proposedThreadName");
78 }
79 this.runnable = runnable;
80 this.determiner = determiner;
81 this.proposedThreadName = proposedThreadName;
82 }
83
84 public ThreadRenamingRunnable(Runnable runnable, String proposedThreadName) {
85 this(runnable, proposedThreadName, null);
86 }
87
88 public void run() {
89 final Thread currentThread = Thread.currentThread();
90 final String oldThreadName = currentThread.getName();
91 final String newThreadName = getNewThreadName(oldThreadName);
92
93
94 boolean renamed = false;
95 if (!oldThreadName.equals(newThreadName)) {
96 try {
97 currentThread.setName(newThreadName);
98 renamed = true;
99 } catch (SecurityException e) {
100 logger.debug(
101 "Failed to rename a thread " +
102 "due to security restriction.", e);
103 }
104 }
105
106
107 try {
108 runnable.run();
109 } finally {
110 if (renamed) {
111
112
113 currentThread.setName(oldThreadName);
114 }
115 }
116 }
117
118 private String getNewThreadName(String currentThreadName) {
119 String newThreadName = null;
120
121 try {
122 ThreadNameDeterminer nameDeterminer = determiner;
123 if (nameDeterminer == null) {
124 nameDeterminer = getThreadNameDeterminer();
125 }
126 newThreadName =
127 nameDeterminer.determineThreadName(
128 currentThreadName, proposedThreadName);
129 } catch (Throwable t) {
130 logger.warn("Failed to determine the thread name", t);
131 }
132
133 return newThreadName == null? currentThreadName : newThreadName;
134 }
135 }