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.InterruptedIOException;
22 import java.net.SocketTimeoutException;
23 import java.nio.channels.ClosedByInterruptException;
24
25 /**
26 * This class handles the different interruption classes.
27 * It can be:
28 * - InterruptedException
29 * - InterruptedIOException (inherits IOException); used in IO
30 * - ClosedByInterruptException (inherits IOException)
31 * , - SocketTimeoutException inherits InterruptedIOException but is not a real
32 * interruption, so we have to distinguish the case. This pattern is unfortunately common.
33 */
34 public class ExceptionUtil {
35
36 /**
37 * @return true if the throwable comes an interruption, false otherwise.
38 */
39 public static boolean isInterrupt(Throwable t) {
40 if (t instanceof InterruptedException) return true;
41 if (t instanceof SocketTimeoutException) return false;
42 return (t instanceof InterruptedIOException);
43 }
44
45 /**
46 * @throws InterruptedIOException if t was an interruption. Does nothing otherwise.
47 */
48 public static void rethrowIfInterrupt(Throwable t) throws InterruptedIOException {
49 InterruptedIOException iie = asInterrupt(t);
50 if (iie != null) throw iie;
51 }
52
53 /**
54 * @return an InterruptedIOException if t was an interruption, null otherwise
55 */
56 public static InterruptedIOException asInterrupt(Throwable t) {
57 if (t instanceof SocketTimeoutException) return null;
58
59 if (t instanceof InterruptedIOException) return (InterruptedIOException) t;
60
61 if (t instanceof InterruptedException) {
62 InterruptedIOException iie = new InterruptedIOException();
63 iie.initCause(t);
64 return iie;
65 }
66
67 return null;
68 }
69
70 private ExceptionUtil() {
71 }
72 }