View Javadoc

1   /**
2    *
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *     http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   */
19  package org.apache.hadoop.hbase.util;
20  
21  import java.io.PrintWriter;
22  import java.lang.Thread.UncaughtExceptionHandler;
23  import java.util.concurrent.LinkedBlockingQueue;
24  import java.util.concurrent.ThreadFactory;
25  import java.util.concurrent.ThreadPoolExecutor;
26  import java.util.concurrent.TimeUnit;
27  import java.util.concurrent.atomic.AtomicInteger;
28  
29  import org.apache.commons.logging.Log;
30  import org.apache.commons.logging.LogFactory;
31  import org.apache.hadoop.classification.InterfaceAudience;
32  import org.apache.hadoop.util.ReflectionUtils;
33  import org.apache.hadoop.util.StringUtils;
34  
35  /**
36   * Thread Utility
37   */
38  @InterfaceAudience.Private
39  public class Threads {
40    protected static final Log LOG = LogFactory.getLog(Threads.class);
41    private static final AtomicInteger poolNumber = new AtomicInteger(1);
42  
43    private static UncaughtExceptionHandler LOGGING_EXCEPTION_HANDLER =
44      new UncaughtExceptionHandler() {
45      @Override
46      public void uncaughtException(Thread t, Throwable e) {
47        LOG.warn("Thread:" + t + " exited with Exception:"
48            + StringUtils.stringifyException(e));
49      }
50    };
51  
52    /**
53     * Utility method that sets name, daemon status and starts passed thread.
54     * @param t thread to run
55     * @return Returns the passed Thread <code>t</code>.
56     */
57    public static Thread setDaemonThreadRunning(final Thread t) {
58      return setDaemonThreadRunning(t, t.getName());
59    }
60  
61    /**
62     * Utility method that sets name, daemon status and starts passed thread.
63     * @param t thread to frob
64     * @param name new name
65     * @return Returns the passed Thread <code>t</code>.
66     */
67    public static Thread setDaemonThreadRunning(final Thread t,
68      final String name) {
69      return setDaemonThreadRunning(t, name, null);
70    }
71  
72    /**
73     * Utility method that sets name, daemon status and starts passed thread.
74     * @param t thread to frob
75     * @param name new name
76     * @param handler A handler to set on the thread.  Pass null if want to
77     * use default handler.
78     * @return Returns the passed Thread <code>t</code>.
79     */
80    public static Thread setDaemonThreadRunning(final Thread t,
81      final String name, final UncaughtExceptionHandler handler) {
82      t.setName(name);
83      if (handler != null) {
84        t.setUncaughtExceptionHandler(handler);
85      }
86      t.setDaemon(true);
87      t.start();
88      return t;
89    }
90  
91    /**
92     * Shutdown passed thread using isAlive and join.
93     * @param t Thread to shutdown
94     */
95    public static void shutdown(final Thread t) {
96      shutdown(t, 0);
97    }
98  
99    /**
100    * Shutdown passed thread using isAlive and join.
101    * @param joinwait Pass 0 if we're to wait forever.
102    * @param t Thread to shutdown
103    */
104   public static void shutdown(final Thread t, final long joinwait) {
105     if (t == null) return;
106     while (t.isAlive()) {
107       try {
108         t.join(joinwait);
109       } catch (InterruptedException e) {
110         LOG.warn(t.getName() + "; joinwait=" + joinwait, e);
111       }
112     }
113   }
114 
115 
116   /**
117    * @param t Waits on the passed thread to die dumping a threaddump every
118    * minute while its up.
119    * @throws InterruptedException
120    */
121   public static void threadDumpingIsAlive(final Thread t)
122   throws InterruptedException {
123     if (t == null) {
124       return;
125     }
126 
127     while (t.isAlive()) {
128       t.join(60 * 1000);
129       if (t.isAlive()) {
130         ReflectionUtils.printThreadInfo(new PrintWriter(System.out),
131             "Automatic Stack Trace every 60 seconds waiting on " +
132             t.getName());
133       }
134     }
135   }
136 
137   /**
138    * If interrupted, just prints out the interrupt on STDOUT, resets interrupt and returns
139    * @param millis How long to sleep for in milliseconds.
140    */
141   public static void sleep(long millis) {
142     try {
143       Thread.sleep(millis);
144     } catch (InterruptedException e) {
145       e.printStackTrace();
146       Thread.currentThread().interrupt();
147     }
148   }
149 
150   /**
151    * Sleeps for the given amount of time even if interrupted. Preserves
152    * the interrupt status.
153    * @param msToWait the amount of time to sleep in milliseconds
154    */
155   public static void sleepWithoutInterrupt(final long msToWait) {
156     long timeMillis = System.currentTimeMillis();
157     long endTime = timeMillis + msToWait;
158     boolean interrupted = false;
159     while (timeMillis < endTime) {
160       try {
161         Thread.sleep(endTime - timeMillis);
162       } catch (InterruptedException ex) {
163         interrupted = true;
164       }
165       timeMillis = System.currentTimeMillis();
166     }
167 
168     if (interrupted) {
169       Thread.currentThread().interrupt();
170     }
171   }
172 
173   /**
174    * Create a new CachedThreadPool with a bounded number as the maximum
175    * thread size in the pool.
176    *
177    * @param maxCachedThread the maximum thread could be created in the pool
178    * @param timeout the maximum time to wait
179    * @param unit the time unit of the timeout argument
180    * @param threadFactory the factory to use when creating new threads
181    * @return threadPoolExecutor the cachedThreadPool with a bounded number
182    * as the maximum thread size in the pool.
183    */
184   public static ThreadPoolExecutor getBoundedCachedThreadPool(
185       int maxCachedThread, long timeout, TimeUnit unit,
186       ThreadFactory threadFactory) {
187     ThreadPoolExecutor boundedCachedThreadPool =
188       new ThreadPoolExecutor(maxCachedThread, maxCachedThread, timeout,
189         unit, new LinkedBlockingQueue<Runnable>(), threadFactory);
190     // allow the core pool threads timeout and terminate
191     boundedCachedThreadPool.allowCoreThreadTimeOut(true);
192     return boundedCachedThreadPool;
193   }
194 
195 
196   /**
197    * Returns a {@link java.util.concurrent.ThreadFactory} that names each created thread uniquely,
198    * with a common prefix.
199    * @param prefix The prefix of every created Thread's name
200    * @return a {@link java.util.concurrent.ThreadFactory} that names threads
201    */
202   public static ThreadFactory getNamedThreadFactory(final String prefix) {
203     SecurityManager s = System.getSecurityManager();
204     final ThreadGroup threadGroup = (s != null) ? s.getThreadGroup() : Thread.currentThread()
205         .getThreadGroup();
206 
207     return new ThreadFactory() {
208       final AtomicInteger threadNumber = new AtomicInteger(1);
209       private final int poolNumber = Threads.poolNumber.getAndIncrement();
210       final ThreadGroup group = threadGroup;
211 
212       @Override
213       public Thread newThread(Runnable r) {
214         final String name = prefix + "-pool" + poolNumber + "-t" + threadNumber.getAndIncrement();
215         return new Thread(group, r, name);
216       }
217     };
218   }
219 
220   /**
221    * Same as {#newDaemonThreadFactory(String, UncaughtExceptionHandler)},
222    * without setting the exception handler.
223    */
224   public static ThreadFactory newDaemonThreadFactory(final String prefix) {
225     return newDaemonThreadFactory(prefix, null);
226   }
227 
228   /**
229    * Get a named {@link ThreadFactory} that just builds daemon threads.
230    * @param prefix name prefix for all threads created from the factory
231    * @param handler unhandles exception handler to set for all threads
232    * @return a thread factory that creates named, daemon threads with
233    *         the supplied exception handler and normal priority
234    */
235   public static ThreadFactory newDaemonThreadFactory(final String prefix,
236       final UncaughtExceptionHandler handler) {
237     final ThreadFactory namedFactory = getNamedThreadFactory(prefix);
238     return new ThreadFactory() {
239       @Override
240       public Thread newThread(Runnable r) {
241         Thread t = namedFactory.newThread(r);
242         if (handler != null) {
243           t.setUncaughtExceptionHandler(handler);
244         } else {
245           t.setUncaughtExceptionHandler(LOGGING_EXCEPTION_HANDLER);
246         }
247         if (!t.isDaemon()) {
248           t.setDaemon(true);
249         }
250         if (t.getPriority() != Thread.NORM_PRIORITY) {
251           t.setPriority(Thread.NORM_PRIORITY);
252         }
253         return t;
254       }
255 
256     };
257   }
258 
259   /** Sets an UncaughtExceptionHandler for the thread which logs the
260    * Exception stack if the thread dies.
261    */
262   public static void setLoggingUncaughtExceptionHandler(Thread t) {
263     t.setUncaughtExceptionHandler(LOGGING_EXCEPTION_HANDLER);
264   }
265 }