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 org.checkerframework.checker.nullness.compatqual.NullableDecl; 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 <a 035 * 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 * } 056 * }</pre> 057 * 058 * <p>Note that this try-catch-finally block is not equivalent to a try-catch-finally block using 059 * try-with-resources. To get the equivalent of that, you must wrap the above code in <i>another</i> 060 * try block in order to catch any exception that may be thrown (including from the call to {@code 061 * close()}). 062 * 063 * <p>This pattern ensures the following: 064 * 065 * <ul> 066 * <li>Each {@code Closeable} resource that is successfully registered will be closed later. 067 * <li>If a {@code Throwable} is thrown in the try block, no exceptions that occur when attempting 068 * to close resources will be thrown from the finally block. The throwable from the try block 069 * will be thrown. 070 * <li>If no exceptions or errors were thrown in the try block, the <i>first</i> exception thrown 071 * by an attempt to close a resource will be thrown. 072 * <li>Any exception caught when attempting to close a resource that is <i>not</i> thrown (because 073 * another exception is already being thrown) is <i>suppressed</i>. 074 * </ul> 075 * 076 * <p>An exception that is suppressed is not thrown. The method of suppression used depends on the 077 * version of Java the code is running on: 078 * 079 * <ul> 080 * <li><b>Java 7+:</b> Exceptions are suppressed by adding them to the exception that <i>will</i> 081 * be thrown using {@code Throwable.addSuppressed(Throwable)}. 082 * <li><b>Java 6:</b> Exceptions are suppressed by logging them instead. 083 * </ul> 084 * 085 * @author Colin Decker 086 * @since 14.0 087 */ 088// Coffee's for {@link Closer closers} only. 089@Beta 090@GwtIncompatible 091public final class Closer implements Closeable { 092 093 /** The suppressor implementation to use for the current Java version. */ 094 private static final Suppressor SUPPRESSOR = 095 SuppressingSuppressor.isAvailable() 096 ? SuppressingSuppressor.INSTANCE 097 : LoggingSuppressor.INSTANCE; 098 099 /** Creates a new {@link Closer}. */ 100 public static Closer create() { 101 return new Closer(SUPPRESSOR); 102 } 103 104 @VisibleForTesting final Suppressor suppressor; 105 106 // only need space for 2 elements in most cases, so try to use the smallest array possible 107 private final Deque<Closeable> stack = new ArrayDeque<>(4); 108 private Throwable thrown; 109 110 @VisibleForTesting 111 Closer(Suppressor suppressor) { 112 this.suppressor = checkNotNull(suppressor); // checkNotNull to satisfy null tests 113 } 114 115 /** 116 * Registers the given {@code closeable} to be closed when this {@code Closer} is {@linkplain 117 * #close closed}. 118 * 119 * @return the given {@code closeable} 120 */ 121 // close. this word no longer has any meaning to me. 122 @CanIgnoreReturnValue 123 public <C extends Closeable> C register(@NullableDecl C closeable) { 124 if (closeable != null) { 125 stack.addFirst(closeable); 126 } 127 128 return closeable; 129 } 130 131 /** 132 * Stores the given throwable and rethrows it. It will be rethrown as is if it is an {@code 133 * IOException}, {@code RuntimeException} or {@code Error}. Otherwise, it will be rethrown wrapped 134 * in a {@code RuntimeException}. <b>Note:</b> Be sure to declare all of the checked exception 135 * types your try block can throw when calling an overload of this method so as to avoid losing 136 * the original exception type. 137 * 138 * <p>This method always throws, and as such should be called as {@code throw closer.rethrow(e);} 139 * to ensure the compiler knows that it will throw. 140 * 141 * @return this method does not return; it always throws 142 * @throws IOException when the given throwable is an IOException 143 */ 144 public RuntimeException rethrow(Throwable e) throws IOException { 145 checkNotNull(e); 146 thrown = e; 147 Throwables.propagateIfPossible(e, IOException.class); 148 throw new RuntimeException(e); 149 } 150 151 /** 152 * Stores the given throwable and rethrows it. It will be rethrown as is if it is an {@code 153 * IOException}, {@code RuntimeException}, {@code Error} or a checked exception of the given type. 154 * Otherwise, it will be rethrown wrapped in a {@code RuntimeException}. <b>Note:</b> Be sure to 155 * declare all of the checked exception types your try block can throw when calling an overload of 156 * this method so as to avoid losing the original exception type. 157 * 158 * <p>This method always throws, and as such should be called as {@code throw closer.rethrow(e, 159 * ...);} to ensure the compiler knows that it will throw. 160 * 161 * @return this method does not return; it always throws 162 * @throws IOException when the given throwable is an IOException 163 * @throws X when the given throwable is of the declared type X 164 */ 165 public <X extends Exception> RuntimeException rethrow(Throwable e, Class<X> declaredType) 166 throws IOException, X { 167 checkNotNull(e); 168 thrown = e; 169 Throwables.propagateIfPossible(e, IOException.class); 170 Throwables.propagateIfPossible(e, declaredType); 171 throw new RuntimeException(e); 172 } 173 174 /** 175 * Stores the given throwable and rethrows it. It will be rethrown as is if it is an {@code 176 * IOException}, {@code RuntimeException}, {@code Error} or a checked exception of either of the 177 * given types. Otherwise, it will be rethrown wrapped in a {@code RuntimeException}. <b>Note:</b> 178 * Be sure to declare all of the checked exception types your try block can throw when calling an 179 * overload of this method so as to avoid losing the original exception type. 180 * 181 * <p>This method always throws, and as such should be called as {@code throw closer.rethrow(e, 182 * ...);} to ensure the compiler knows that it will throw. 183 * 184 * @return this method does not return; it always throws 185 * @throws IOException when the given throwable is an IOException 186 * @throws X1 when the given throwable is of the declared type X1 187 * @throws X2 when the given throwable is of the declared type X2 188 */ 189 public <X1 extends Exception, X2 extends Exception> RuntimeException rethrow( 190 Throwable e, Class<X1> declaredType1, Class<X2> declaredType2) throws IOException, X1, X2 { 191 checkNotNull(e); 192 thrown = e; 193 Throwables.propagateIfPossible(e, IOException.class); 194 Throwables.propagateIfPossible(e, declaredType1, declaredType2); 195 throw new RuntimeException(e); 196 } 197 198 /** 199 * Closes all {@code Closeable} instances that have been added to this {@code Closer}. If an 200 * exception was thrown in the try block and passed to one of the {@code exceptionThrown} methods, 201 * any exceptions thrown when attempting to close a closeable will be suppressed. Otherwise, the 202 * <i>first</i> exception to be thrown from an attempt to close a closeable will be thrown and any 203 * additional exceptions that are thrown after that will be suppressed. 204 */ 205 @Override 206 public void close() throws IOException { 207 Throwable throwable = thrown; 208 209 // close closeables in LIFO order 210 while (!stack.isEmpty()) { 211 Closeable closeable = stack.removeFirst(); 212 try { 213 closeable.close(); 214 } catch (Throwable e) { 215 if (throwable == null) { 216 throwable = e; 217 } else { 218 suppressor.suppress(closeable, throwable, e); 219 } 220 } 221 } 222 223 if (thrown == null && throwable != null) { 224 Throwables.propagateIfPossible(throwable, IOException.class); 225 throw new AssertionError(throwable); // not possible 226 } 227 } 228 229 /** Suppression strategy interface. */ 230 @VisibleForTesting 231 interface Suppressor { 232 /** 233 * Suppresses the given exception ({@code suppressed}) which was thrown when attempting to close 234 * the given closeable. {@code thrown} is the exception that is actually being thrown from the 235 * method. Implementations of this method should not throw under any circumstances. 236 */ 237 void suppress(Closeable closeable, Throwable thrown, Throwable suppressed); 238 } 239 240 /** Suppresses exceptions by logging them. */ 241 @VisibleForTesting 242 static final class LoggingSuppressor implements Suppressor { 243 244 static final LoggingSuppressor INSTANCE = new LoggingSuppressor(); 245 246 @Override 247 public void suppress(Closeable closeable, Throwable thrown, Throwable suppressed) { 248 // log to the same place as Closeables 249 Closeables.logger.log( 250 Level.WARNING, "Suppressing exception thrown when closing " + closeable, suppressed); 251 } 252 } 253 254 /** 255 * Suppresses exceptions by adding them to the exception that will be thrown using JDK7's 256 * addSuppressed(Throwable) mechanism. 257 */ 258 @VisibleForTesting 259 static final class SuppressingSuppressor implements Suppressor { 260 261 static final SuppressingSuppressor INSTANCE = new SuppressingSuppressor(); 262 263 static boolean isAvailable() { 264 return addSuppressed != null; 265 } 266 267 static final Method addSuppressed = getAddSuppressed(); 268 269 private static Method getAddSuppressed() { 270 try { 271 return Throwable.class.getMethod("addSuppressed", Throwable.class); 272 } catch (Throwable e) { 273 return null; 274 } 275 } 276 277 @Override 278 public void suppress(Closeable closeable, Throwable thrown, Throwable suppressed) { 279 // ensure no exceptions from addSuppressed 280 if (thrown == suppressed) { 281 return; 282 } 283 try { 284 addSuppressed.invoke(thrown, suppressed); 285 } catch (Throwable e) { 286 // if, somehow, IllegalAccessException or another exception is thrown, fall back to logging 287 LoggingSuppressor.INSTANCE.suppress(closeable, thrown, suppressed); 288 } 289 } 290 } 291}