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 public static Thread setDaemonThreadRunning(final Thread t) {
41 return setDaemonThreadRunning(t, t.getName());
42 }
43
44
45
46
47
48
49
50 public static Thread setDaemonThreadRunning(final Thread t,
51 final String name) {
52 return setDaemonThreadRunning(t, name, null);
53 }
54
55
56
57
58
59
60
61
62
63 public static Thread setDaemonThreadRunning(final Thread t,
64 final String name, final UncaughtExceptionHandler handler) {
65 t.setName(name);
66 if (handler != null) {
67 t.setUncaughtExceptionHandler(handler);
68 }
69 t.setDaemon(true);
70 t.start();
71 return t;
72 }
73
74
75
76
77
78 public static void shutdown(final Thread t) {
79 shutdown(t, 0);
80 }
81
82
83
84
85
86
87 public static void shutdown(final Thread t, final long joinwait) {
88 if (t == null) return;
89 while (t.isAlive()) {
90 try {
91 t.join(joinwait);
92 } catch (InterruptedException e) {
93 LOG.warn(t.getName() + "; joinwait=" + joinwait, e);
94 }
95 }
96 }
97
98
99
100
101
102
103
104 public static void threadDumpingIsAlive(final Thread t)
105 throws InterruptedException {
106 if (t == null) {
107 return;
108 }
109 long startTime = System.currentTimeMillis();
110 while (t.isAlive()) {
111 Thread.sleep(1000);
112 if (System.currentTimeMillis() - startTime > 60000) {
113 startTime = System.currentTimeMillis();
114 ReflectionUtils.printThreadInfo(new PrintWriter(System.out),
115 "Automatic Stack Trace every 60 seconds waiting on " +
116 t.getName());
117 }
118 }
119 }
120
121
122
123
124 public static void sleep(int millis) {
125 try {
126 Thread.sleep(millis);
127 } catch (InterruptedException e) {
128 e.printStackTrace();
129 }
130 }
131 }