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
38
39
40
41
42 public static ThreadNameDeterminer getThreadNameDeterminer() {
43 return threadNameDeterminer;
44 }
45
46
47
48
49
50
51
52
53
54
55
56 public static void setThreadNameDeterminer(ThreadNameDeterminer threadNameDeterminer) {
57 if (threadNameDeterminer == null) {
58 throw new NullPointerException("threadNameDeterminer");
59 }
60 ThreadRenamingRunnable.threadNameDeterminer = threadNameDeterminer;
61 }
62
63 private final Runnable runnable;
64 private final String proposedThreadName;
65
66
67
68
69
70
71 public ThreadRenamingRunnable(Runnable runnable, String proposedThreadName) {
72 if (runnable == null) {
73 throw new NullPointerException("runnable");
74 }
75 if (proposedThreadName == null) {
76 throw new NullPointerException("proposedThreadName");
77 }
78 this.runnable = runnable;
79 this.proposedThreadName = proposedThreadName;
80 }
81
82 public void run() {
83 final Thread currentThread = Thread.currentThread();
84 final String oldThreadName = currentThread.getName();
85 final String newThreadName = getNewThreadName(oldThreadName);
86
87
88 boolean renamed = false;
89 if (!oldThreadName.equals(newThreadName)) {
90 try {
91 currentThread.setName(newThreadName);
92 renamed = true;
93 } catch (SecurityException e) {
94 logger.debug(
95 "Failed to rename a thread " +
96 "due to security restriction.", e);
97 }
98 }
99
100
101 try {
102 runnable.run();
103 } finally {
104 if (renamed) {
105
106
107 currentThread.setName(oldThreadName);
108 }
109 }
110 }
111
112 private String getNewThreadName(String currentThreadName) {
113 String newThreadName = null;
114
115 try {
116 newThreadName =
117 getThreadNameDeterminer().determineThreadName(
118 currentThreadName, proposedThreadName);
119 } catch (Throwable t) {
120 logger.warn("Failed to determine the thread name", t);
121 }
122
123 return newThreadName == null? currentThreadName : newThreadName;
124 }
125 }