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