1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.hadoop.hbase.util;
21
22 import org.apache.commons.logging.Log;
23 import org.apache.commons.logging.LogFactory;
24 import java.io.PrintWriter;
25 import org.apache.hadoop.util.ReflectionUtils;
26
27 import java.lang.Thread.UncaughtExceptionHandler;
28
29
30
31
32 public class Threads {
33 protected static final Log LOG = LogFactory.getLog(Threads.class);
34
35
36
37
38
39
40
41 public static Thread setDaemonThreadRunning(final Thread t,
42 final String name) {
43 return setDaemonThreadRunning(t, name, null);
44 }
45
46
47
48
49
50
51
52
53
54 public static Thread setDaemonThreadRunning(final Thread t,
55 final String name, final UncaughtExceptionHandler handler) {
56 t.setName(name);
57 if (handler != null) {
58 t.setUncaughtExceptionHandler(handler);
59 }
60 t.setDaemon(true);
61 t.start();
62 return t;
63 }
64
65
66
67
68
69 public static void shutdown(final Thread t) {
70 shutdown(t, 0);
71 }
72
73
74
75
76
77
78 public static void shutdown(final Thread t, final long joinwait) {
79 if (t == null) return;
80 while (t.isAlive()) {
81 try {
82 t.join(joinwait);
83 } catch (InterruptedException e) {
84 LOG.warn(t.getName() + "; joinwait=" + joinwait, e);
85 }
86 }
87 }
88
89
90
91
92
93
94
95 public static void threadDumpingIsAlive(final Thread t)
96 throws InterruptedException {
97 if (t == null) {
98 return;
99 }
100 long startTime = System.currentTimeMillis();
101 while (t.isAlive()) {
102 Thread.sleep(1000);
103 if (System.currentTimeMillis() - startTime > 60000) {
104 startTime = System.currentTimeMillis();
105 ReflectionUtils.printThreadInfo(new PrintWriter(System.out),
106 "Automatic Stack Trace every 60 seconds waiting on " +
107 t.getName());
108 }
109 }
110 }
111
112
113
114
115 public static void sleep(int millis) {
116 try {
117 Thread.sleep(millis);
118 } catch (InterruptedException e) {
119 e.printStackTrace();
120 }
121 }
122 }