001/* 002 * Copyright (C) 2012 The Guava Authors 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 005 * in compliance with the License. You may obtain a copy of the License at 006 * 007 * http://www.apache.org/licenses/LICENSE-2.0 008 * 009 * Unless required by applicable law or agreed to in writing, software distributed under the License 010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 011 * or implied. See the License for the specific language governing permissions and limitations under 012 * the License. 013 */ 014 015package com.google.common.io; 016 017import static com.google.common.base.Preconditions.checkNotNull; 018 019import com.google.common.annotations.Beta; 020import com.google.common.annotations.GwtIncompatible; 021import com.google.common.annotations.VisibleForTesting; 022import com.google.common.base.Throwables; 023import com.google.errorprone.annotations.CanIgnoreReturnValue; 024import java.io.Closeable; 025import java.io.IOException; 026import java.lang.reflect.Method; 027import java.util.ArrayDeque; 028import java.util.Deque; 029import java.util.logging.Level; 030import javax.annotation.Nullable; 031 032/** 033 * A {@link Closeable} that collects {@code Closeable} resources and closes them all when it is 034 * {@linkplain #close closed}. This is intended to approximately emulate the behavior of Java 7's 035 * <a href="http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html" 036 * >try-with-resources</a> statement in JDK6-compatible code. Running on Java 7, code using this 037 * should be approximately equivalent in behavior to the same code written with try-with-resources. 038 * Running on Java 6, exceptions that cannot be thrown must be logged rather than being added to the 039 * thrown exception as a suppressed exception. 040 * 041 * <p>This class is intended to be used in the following pattern: 042 * 043 * <pre> {@code 044 * Closer closer = Closer.create(); 045 * try { 046 * InputStream in = closer.register(openInputStream()); 047 * OutputStream out = closer.register(openOutputStream()); 048 * // do stuff 049 * } catch (Throwable e) { 050 * // ensure that any checked exception types other than IOException that could be thrown are 051 * // provided here, e.g. throw closer.rethrow(e, CheckedException.class); 052 * throw closer.rethrow(e); 053 * } finally { 054 * closer.close(); 055 * }}</pre> 056 * 057 * <p>Note that this try-catch-finally block is not equivalent to a try-catch-finally block using 058 * try-with-resources. To get the equivalent of that, you must wrap the above code in <i>another</i> 059 * try block in order to catch any exception that may be thrown (including from the call to 060 * {@code close()}). 061 * 062 * <p>This pattern ensures the following: 063 * 064 * <ul> 065 * <li>Each {@code Closeable} resource that is successfully registered will be closed later. 066 * <li>If a {@code Throwable} is thrown in the try block, no exceptions that occur when attempting 067 * to close resources will be thrown from the finally block. The throwable from the try block 068 * will be thrown. 069 * <li>If no exceptions or errors were thrown in the try block, the <i>first</i> exception thrown by 070 * an attempt to close a resource will be thrown. 071 * <li>Any exception caught when attempting to close a resource that is <i>not</i> thrown (because 072 * another exception is already being thrown) is <i>suppressed</i>. 073 * </ul> 074 * 075 * <p>An exception that is suppressed is not thrown. The method of suppression used depends on the 076 * version of Java the code is running on: 077 * 078 * <ul> 079 * <li><b>Java 7+:</b> Exceptions are suppressed by adding them to the exception that <i>will</i> be 080 * thrown using {@code Throwable.addSuppressed(Throwable)}. 081 * <li><b>Java 6:</b> Exceptions are suppressed by logging them instead. 082 * </ul> 083 * 084 * @author Colin Decker 085 * @since 14.0 086 */ 087// Coffee's for {@link Closer closers} only. 088@Beta 089@GwtIncompatible 090public final class Closer implements Closeable { 091 092 /** 093 * The suppressor implementation to use for the current Java version. 094 */ 095 private static final Suppressor SUPPRESSOR = 096 SuppressingSuppressor.isAvailable() 097 ? SuppressingSuppressor.INSTANCE 098 : LoggingSuppressor.INSTANCE; 099 100 /** 101 * Creates a new {@link Closer}. 102 */ 103 public static Closer create() { 104 return new Closer(SUPPRESSOR); 105 } 106 107 @VisibleForTesting final Suppressor suppressor; 108 109 // only need space for 2 elements in most cases, so try to use the smallest array possible 110 private final Deque<Closeable> stack = new ArrayDeque<>(4); 111 private Throwable thrown; 112 113 @VisibleForTesting 114 Closer(Suppressor suppressor) { 115 this.suppressor = checkNotNull(suppressor); // checkNotNull to satisfy null tests 116 } 117 118 /** 119 * Registers the given {@code closeable} to be closed when this {@code Closer} is 120 * {@linkplain #close closed}. 121 * 122 * @return the given {@code closeable} 123 */ 124 // close. this word no longer has any meaning to me. 125 @CanIgnoreReturnValue 126 public <C extends Closeable> C register(@Nullable C closeable) { 127 if (closeable != null) { 128 stack.addFirst(closeable); 129 } 130 131 return closeable; 132 } 133 134 /** 135 * Stores the given throwable and rethrows it. It will be rethrown as is if it is an 136 * {@code IOException}, {@code RuntimeException} or {@code Error}. Otherwise, it will be rethrown 137 * wrapped in a {@code RuntimeException}. <b>Note:</b> Be sure to declare all of the checked 138 * exception types your try block can throw when calling an overload of this method so as to avoid 139 * losing the original exception type. 140 * 141 * <p>This method always throws, and as such should be called as {@code throw closer.rethrow(e);} 142 * to ensure the compiler knows that it will throw. 143 * 144 * @return this method does not return; it always throws 145 * @throws IOException when the given throwable is an IOException 146 */ 147 public RuntimeException rethrow(Throwable e) throws IOException { 148 checkNotNull(e); 149 thrown = e; 150 Throwables.propagateIfPossible(e, IOException.class); 151 throw new RuntimeException(e); 152 } 153 154 /** 155 * Stores the given throwable and rethrows it. It will be rethrown as is if it is an 156 * {@code IOException}, {@code RuntimeException}, {@code Error} or a checked exception of the 157 * given type. Otherwise, it will be rethrown wrapped in a {@code RuntimeException}. <b>Note:</b> 158 * Be sure to declare all of the checked exception types your try block can throw when calling an 159 * overload of this method so as to avoid losing the original exception type. 160 * 161 * <p>This method always throws, and as such should be called as 162 * {@code throw closer.rethrow(e, ...);} to ensure the compiler knows that it will throw. 163 * 164 * @return this method does not return; it always throws 165 * @throws IOException when the given throwable is an IOException 166 * @throws X when the given throwable is of the declared type X 167 */ 168 public <X extends Exception> RuntimeException rethrow(Throwable e, Class<X> declaredType) 169 throws IOException, X { 170 checkNotNull(e); 171 thrown = e; 172 Throwables.propagateIfPossible(e, IOException.class); 173 Throwables.propagateIfPossible(e, declaredType); 174 throw new RuntimeException(e); 175 } 176 177 /** 178 * Stores the given throwable and rethrows it. It will be rethrown as is if it is an 179 * {@code IOException}, {@code RuntimeException}, {@code Error} or a checked exception of either 180 * of the given types. Otherwise, it will be rethrown wrapped in a {@code RuntimeException}. 181 * <b>Note:</b> Be sure to declare all of the checked exception types your try block can throw 182 * when calling an overload of this method so as to avoid losing the original exception type. 183 * 184 * <p>This method always throws, and as such should be called as 185 * {@code throw closer.rethrow(e, ...);} to ensure the compiler knows that it will throw. 186 * 187 * @return this method does not return; it always throws 188 * @throws IOException when the given throwable is an IOException 189 * @throws X1 when the given throwable is of the declared type X1 190 * @throws X2 when the given throwable is of the declared type X2 191 */ 192 public <X1 extends Exception, X2 extends Exception> RuntimeException rethrow( 193 Throwable e, Class<X1> declaredType1, Class<X2> declaredType2) throws IOException, X1, X2 { 194 checkNotNull(e); 195 thrown = e; 196 Throwables.propagateIfPossible(e, IOException.class); 197 Throwables.propagateIfPossible(e, declaredType1, declaredType2); 198 throw new RuntimeException(e); 199 } 200 201 /** 202 * Closes all {@code Closeable} instances that have been added to this {@code Closer}. If an 203 * exception was thrown in the try block and passed to one of the {@code exceptionThrown} methods, 204 * any exceptions thrown when attempting to close a closeable will be suppressed. Otherwise, the 205 * <i>first</i> exception to be thrown from an attempt to close a closeable will be thrown and any 206 * additional exceptions that are thrown after that will be suppressed. 207 */ 208 @Override 209 public void close() throws IOException { 210 Throwable throwable = thrown; 211 212 // close closeables in LIFO order 213 while (!stack.isEmpty()) { 214 Closeable closeable = stack.removeFirst(); 215 try { 216 closeable.close(); 217 } catch (Throwable e) { 218 if (throwable == null) { 219 throwable = e; 220 } else { 221 suppressor.suppress(closeable, throwable, e); 222 } 223 } 224 } 225 226 if (thrown == null && throwable != null) { 227 Throwables.propagateIfPossible(throwable, IOException.class); 228 throw new AssertionError(throwable); // not possible 229 } 230 } 231 232 /** 233 * Suppression strategy interface. 234 */ 235 @VisibleForTesting 236 interface Suppressor { 237 /** 238 * Suppresses the given exception ({@code suppressed}) which was thrown when attempting to close 239 * the given closeable. {@code thrown} is the exception that is actually being thrown from the 240 * method. Implementations of this method should not throw under any circumstances. 241 */ 242 void suppress(Closeable closeable, Throwable thrown, Throwable suppressed); 243 } 244 245 /** 246 * Suppresses exceptions by logging them. 247 */ 248 @VisibleForTesting 249 static final class LoggingSuppressor implements Suppressor { 250 251 static final LoggingSuppressor INSTANCE = new LoggingSuppressor(); 252 253 @Override 254 public void suppress(Closeable closeable, Throwable thrown, Throwable suppressed) { 255 // log to the same place as Closeables 256 Closeables.logger.log( 257 Level.WARNING, "Suppressing exception thrown when closing " + closeable, suppressed); 258 } 259 } 260 261 /** 262 * Suppresses exceptions by adding them to the exception that will be thrown using JDK7's 263 * addSuppressed(Throwable) mechanism. 264 */ 265 @VisibleForTesting 266 static final class SuppressingSuppressor implements Suppressor { 267 268 static final SuppressingSuppressor INSTANCE = new SuppressingSuppressor(); 269 270 static boolean isAvailable() { 271 return addSuppressed != null; 272 } 273 274 static final Method addSuppressed = getAddSuppressed(); 275 276 private static Method getAddSuppressed() { 277 try { 278 return Throwable.class.getMethod("addSuppressed", Throwable.class); 279 } catch (Throwable e) { 280 return null; 281 } 282 } 283 284 @Override 285 public void suppress(Closeable closeable, Throwable thrown, Throwable suppressed) { 286 // ensure no exceptions from addSuppressed 287 if (thrown == suppressed) { 288 return; 289 } 290 try { 291 addSuppressed.invoke(thrown, suppressed); 292 } catch (Throwable e) { 293 // if, somehow, IllegalAccessException or another exception is thrown, fall back to logging 294 LoggingSuppressor.INSTANCE.suppress(closeable, thrown, suppressed); 295 } 296 } 297 } 298}