View Javadoc

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