001/** 002 * 003 * Licensed to the Apache Software Foundation (ASF) under one 004 * or more contributor license agreements. See the NOTICE file 005 * distributed with this work for additional information 006 * regarding copyright ownership. The ASF licenses this file 007 * to you under the Apache License, Version 2.0 (the 008 * "License"); you may not use this file except in compliance 009 * with the License. You may obtain a copy of the License at 010 * 011 * http://www.apache.org/licenses/LICENSE-2.0 012 * 013 * Unless required by applicable law or agreed to in writing, software 014 * distributed under the License is distributed on an "AS IS" BASIS, 015 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 016 * See the License for the specific language governing permissions and 017 * limitations under the License. 018 */ 019package org.apache.hadoop.hbase.util; 020 021import java.io.InterruptedIOException; 022import java.net.SocketTimeoutException; 023import java.nio.channels.ClosedByInterruptException; 024 025import org.apache.yetus.audience.InterfaceAudience; 026 027/** 028 * This class handles the different interruption classes. 029 * It can be: 030 * - InterruptedException 031 * - InterruptedIOException (inherits IOException); used in IO 032 * - ClosedByInterruptException (inherits IOException) 033 * - SocketTimeoutException inherits InterruptedIOException but is not a real 034 * interruption, so we have to distinguish the case. This pattern is unfortunately common. 035 */ 036@InterfaceAudience.Private 037public class ExceptionUtil { 038 039 /** 040 * @return true if the throwable comes an interruption, false otherwise. 041 */ 042 public static boolean isInterrupt(Throwable t) { 043 if (t instanceof InterruptedException) return true; 044 if (t instanceof SocketTimeoutException) return false; 045 return (t instanceof InterruptedIOException || t instanceof ClosedByInterruptException); 046 } 047 048 /** 049 * @throws InterruptedIOException if t was an interruption. Does nothing otherwise. 050 */ 051 public static void rethrowIfInterrupt(Throwable t) throws InterruptedIOException { 052 InterruptedIOException iie = asInterrupt(t); 053 if (iie != null) throw iie; 054 } 055 056 /** 057 * @return an InterruptedIOException if t was an interruption, null otherwise 058 */ 059 public static InterruptedIOException asInterrupt(Throwable t) { 060 if (t instanceof SocketTimeoutException) return null; 061 062 if (t instanceof InterruptedIOException) return (InterruptedIOException) t; 063 064 if (t instanceof InterruptedException || t instanceof ClosedByInterruptException) { 065 InterruptedIOException iie = 066 new InterruptedIOException("Origin: " + t.getClass().getSimpleName()); 067 iie.initCause(t); 068 return iie; 069 } 070 071 return null; 072 } 073 074 private ExceptionUtil() { 075 } 076}