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.classification.InterfaceStability;
33  import org.apache.hadoop.util.ReflectionUtils;
34  
35  /**
36   * Thread Utility
37   */
38  @InterfaceAudience.Public
39  @InterfaceStability.Stable
40  public class Threads {
41    protected static final Log LOG = LogFactory.getLog(Threads.class);
42    private static final AtomicInteger poolNumber = new AtomicInteger(1);
43    /**
44     * Utility method that sets name, daemon status and starts passed thread.
45     * @param t thread to run
46     * @return Returns the passed Thread <code>t</code>.
47     */
48    public static Thread setDaemonThreadRunning(final Thread t) {
49      return setDaemonThreadRunning(t, t.getName());
50    }
51  
52    /**
53     * Utility method that sets name, daemon status and starts passed thread.
54     * @param t thread to frob
55     * @param name new name
56     * @return Returns the passed Thread <code>t</code>.
57     */
58    public static Thread setDaemonThreadRunning(final Thread t,
59      final String name) {
60      return setDaemonThreadRunning(t, name, null);
61    }
62  
63    /**
64     * Utility method that sets name, daemon status and starts passed thread.
65     * @param t thread to frob
66     * @param name new name
67     * @param handler A handler to set on the thread.  Pass null if want to
68     * use default handler.
69     * @return Returns the passed Thread <code>t</code>.
70     */
71    public static Thread setDaemonThreadRunning(final Thread t,
72      final String name, final UncaughtExceptionHandler handler) {
73      t.setName(name);
74      if (handler != null) {
75        t.setUncaughtExceptionHandler(handler);
76      }
77      t.setDaemon(true);
78      t.start();
79      return t;
80    }
81  
82    /**
83     * Shutdown passed thread using isAlive and join.
84     * @param t Thread to shutdown
85     */
86    public static void shutdown(final Thread t) {
87      shutdown(t, 0);
88    }
89  
90    /**
91     * Shutdown passed thread using isAlive and join.
92     * @param joinwait Pass 0 if we're to wait forever.
93     * @param t Thread to shutdown
94     */
95    public static void shutdown(final Thread t, final long joinwait) {
96      if (t == null) return;
97      while (t.isAlive()) {
98        try {
99          t.join(joinwait);
100       } catch (InterruptedException e) {
101         LOG.warn(t.getName() + "; joinwait=" + joinwait, e);
102       }
103     }
104   }
105 
106 
107   /**
108    * @param t Waits on the passed thread to die dumping a threaddump every
109    * minute while its up.
110    * @throws InterruptedException
111    */
112   public static void threadDumpingIsAlive(final Thread t)
113   throws InterruptedException {
114     if (t == null) {
115       return;
116     }
117 
118     while (t.isAlive()) {
119       t.join(60 * 1000);
120       if (t.isAlive()) {
121         ReflectionUtils.printThreadInfo(new PrintWriter(System.out),
122             "Automatic Stack Trace every 60 seconds waiting on " +
123             t.getName());
124       }
125     }
126   }
127 
128   /**
129    * @param millis How long to sleep for in milliseconds.
130    */
131   public static void sleep(long millis) {
132     try {
133       Thread.sleep(millis);
134     } catch (InterruptedException e) {
135       e.printStackTrace();
136     }
137   }
138 
139   /**
140    * Sleeps for the given amount of time even if interrupted. Preserves
141    * the interrupt status.
142    * @param msToWait the amount of time to sleep in milliseconds
143    */
144   public static void sleepWithoutInterrupt(final long msToWait) {
145     long timeMillis = System.currentTimeMillis();
146     long endTime = timeMillis + msToWait;
147     boolean interrupted = false;
148     while (timeMillis < endTime) {
149       try {
150         Thread.sleep(endTime - timeMillis);
151       } catch (InterruptedException ex) {
152         interrupted = true;
153       }
154       timeMillis = System.currentTimeMillis();
155     }
156 
157     if (interrupted) {
158       Thread.currentThread().interrupt();
159     }
160   }
161 
162   /**
163    * Create a new CachedThreadPool with a bounded number as the maximum 
164    * thread size in the pool.
165    * 
166    * @param maxCachedThread the maximum thread could be created in the pool
167    * @param timeout the maximum time to wait
168    * @param unit the time unit of the timeout argument
169    * @param threadFactory the factory to use when creating new threads
170    * @return threadPoolExecutor the cachedThreadPool with a bounded number 
171    * as the maximum thread size in the pool. 
172    */
173   public static ThreadPoolExecutor getBoundedCachedThreadPool(
174       int maxCachedThread, long timeout, TimeUnit unit,
175       ThreadFactory threadFactory) {
176     ThreadPoolExecutor boundedCachedThreadPool =
177       new ThreadPoolExecutor(maxCachedThread, maxCachedThread, timeout,
178         TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), threadFactory);
179     // allow the core pool threads timeout and terminate
180     boundedCachedThreadPool.allowCoreThreadTimeOut(true);
181     return boundedCachedThreadPool;
182   }
183   
184   
185   /**
186    * Returns a {@link java.util.concurrent.ThreadFactory} that names each created thread uniquely,
187    * with a common prefix.
188    * @param prefix The prefix of every created Thread's name
189    * @return a {@link java.util.concurrent.ThreadFactory} that names threads
190    */
191   public static ThreadFactory getNamedThreadFactory(final String prefix) {
192     SecurityManager s = System.getSecurityManager();
193     final ThreadGroup threadGroup = (s != null) ? s.getThreadGroup() : Thread.currentThread()
194         .getThreadGroup();
195 
196     return new ThreadFactory() {
197       final AtomicInteger threadNumber = new AtomicInteger(1);
198       private final int poolNumber = Threads.poolNumber.getAndIncrement();
199       final ThreadGroup group = threadGroup;
200 
201       @Override
202       public Thread newThread(Runnable r) {
203         final String name = prefix + "-pool-" + poolNumber + "-thread-"
204             + threadNumber.getAndIncrement();
205         return new Thread(group, r, name);
206       }
207     };
208   }
209 
210   /**
211    * Same as {#newDaemonThreadFactory(String, UncaughtExceptionHandler)},
212    * without setting the exception handler.
213    */
214   public static ThreadFactory newDaemonThreadFactory(final String prefix) {
215     return newDaemonThreadFactory(prefix, null);
216   }
217 
218   /**
219    * Get a named {@link ThreadFactory} that just builds daemon threads.
220    * @param prefix name prefix for all threads created from the factory
221    * @param handler unhandles exception handler to set for all threads
222    * @return a thread factory that creates named, daemon threads with
223    *         the supplied exception handler and normal priority
224    */
225   public static ThreadFactory newDaemonThreadFactory(final String prefix,
226       final UncaughtExceptionHandler handler) {
227     final ThreadFactory namedFactory = getNamedThreadFactory(prefix);
228     return new ThreadFactory() {
229       @Override
230       public Thread newThread(Runnable r) {
231         Thread t = namedFactory.newThread(r);
232         if (handler != null) {
233           t.setUncaughtExceptionHandler(handler);
234         }
235         if (!t.isDaemon()) {
236           t.setDaemon(true);
237         }
238         if (t.getPriority() != Thread.NORM_PRIORITY) {
239           t.setPriority(Thread.NORM_PRIORITY);
240         }
241         return t;
242       }
243 
244     };
245   }
246 }