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; 018import static com.google.common.base.Throwables.throwIfInstanceOf; 019import static com.google.common.base.Throwables.throwIfUnchecked; 020 021import com.google.common.annotations.GwtIncompatible; 022import com.google.common.annotations.J2ktIncompatible; 023import com.google.common.annotations.VisibleForTesting; 024import com.google.errorprone.annotations.CanIgnoreReturnValue; 025import java.io.Closeable; 026import java.io.IOException; 027import java.util.ArrayDeque; 028import java.util.Deque; 029import java.util.logging.Level; 030import org.checkerframework.checker.nullness.qual.Nullable; 031 032/** 033 * A {@link Closeable} that collects {@code Closeable} resources and closes them all when it is 034 * {@linkplain #close closed}. This was 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. Code using this should be 037 * approximately equivalent in behavior to the same code written with try-with-resources. 038 * 039 * <p>This class is intended to be used in the following pattern: 040 * 041 * <pre>{@code 042 * Closer closer = Closer.create(); 043 * try { 044 * InputStream in = closer.register(openInputStream()); 045 * OutputStream out = closer.register(openOutputStream()); 046 * // do stuff 047 * } catch (Throwable e) { 048 * // ensure that any checked exception types other than IOException that could be thrown are 049 * // provided here, e.g. throw closer.rethrow(e, CheckedException.class); 050 * throw closer.rethrow(e); 051 * } finally { 052 * closer.close(); 053 * } 054 * }</pre> 055 * 056 * <p>Note that this try-catch-finally block is not equivalent to a try-catch-finally block using 057 * try-with-resources. To get the equivalent of that, you must wrap the above code in <i>another</i> 058 * try block in order to catch any exception that may be thrown (including from the call to {@code 059 * close()}). 060 * 061 * <p>This pattern ensures the following: 062 * 063 * <ul> 064 * <li>Each {@code Closeable} resource that is successfully registered will be closed later. 065 * <li>If a {@code Throwable} is thrown in the try block, no exceptions that occur when attempting 066 * to close resources will be thrown from the finally block. The throwable from the try block 067 * will be thrown. 068 * <li>If no exceptions or errors were thrown in the try block, the <i>first</i> exception thrown 069 * by an attempt to close a resource will be thrown. 070 * <li>Any exception caught when attempting to close a resource that is <i>not</i> thrown (because 071 * another exception is already being thrown) is <i>suppressed</i>. 072 * </ul> 073 * 074 * <p>An exception that is suppressed is added to the exception that <i>will</i> be thrown using 075 * {@code Throwable.addSuppressed(Throwable)}. 076 * 077 * @author Colin Decker 078 * @since 14.0 079 */ 080// Coffee's for {@link Closer closers} only. 081@J2ktIncompatible 082@GwtIncompatible 083public final class Closer implements Closeable { 084 /** Creates a new {@link Closer}. */ 085 public static Closer create() { 086 return new Closer(SUPPRESSING_SUPPRESSOR); 087 } 088 089 @VisibleForTesting final Suppressor suppressor; 090 091 // only need space for 2 elements in most cases, so try to use the smallest array possible 092 private final Deque<Closeable> stack = new ArrayDeque<>(4); 093 private @Nullable Throwable thrown; 094 095 @VisibleForTesting 096 Closer(Suppressor suppressor) { 097 this.suppressor = checkNotNull(suppressor); // checkNotNull to satisfy null tests 098 } 099 100 /** 101 * Registers the given {@code closeable} to be closed when this {@code Closer} is {@linkplain 102 * #close closed}. 103 * 104 * @return the given {@code closeable} 105 */ 106 // close. this word no longer has any meaning to me. 107 @CanIgnoreReturnValue 108 @ParametricNullness 109 public <C extends @Nullable Closeable> C register(@ParametricNullness C closeable) { 110 if (closeable != null) { 111 stack.addFirst(closeable); 112 } 113 114 return closeable; 115 } 116 117 /** 118 * Stores the given throwable and rethrows it. It will be rethrown as is if it is an {@code 119 * IOException}, {@code RuntimeException} or {@code Error}. Otherwise, it will be rethrown wrapped 120 * in a {@code RuntimeException}. <b>Note:</b> Be sure to declare all of the checked exception 121 * types your try block can throw when calling an overload of this method so as to avoid losing 122 * the original exception type. 123 * 124 * <p>This method always throws, and as such should be called as {@code throw closer.rethrow(e);} 125 * to ensure the compiler knows that it will throw. 126 * 127 * @return this method does not return; it always throws 128 * @throws IOException when the given throwable is an IOException 129 */ 130 public RuntimeException rethrow(Throwable e) throws IOException { 131 checkNotNull(e); 132 thrown = e; 133 throwIfInstanceOf(e, IOException.class); 134 throwIfUnchecked(e); 135 throw new RuntimeException(e); 136 } 137 138 /** 139 * Stores the given throwable and rethrows it. It will be rethrown as is if it is an {@code 140 * IOException}, {@code RuntimeException}, {@code Error} or a checked exception of the given type. 141 * Otherwise, it will be rethrown wrapped in a {@code RuntimeException}. <b>Note:</b> Be sure to 142 * declare all of the checked exception types your try block can throw when calling an overload of 143 * this method so as to avoid losing the original exception type. 144 * 145 * <p>This method always throws, and as such should be called as {@code throw closer.rethrow(e, 146 * ...);} to ensure the compiler knows that it will throw. 147 * 148 * @return this method does not return; it always throws 149 * @throws IOException when the given throwable is an IOException 150 * @throws X when the given throwable is of the declared type X 151 */ 152 public <X extends Exception> RuntimeException rethrow(Throwable e, Class<X> declaredType) 153 throws IOException, X { 154 checkNotNull(e); 155 thrown = e; 156 throwIfInstanceOf(e, IOException.class); 157 throwIfInstanceOf(e, declaredType); 158 throwIfUnchecked(e); 159 throw new RuntimeException(e); 160 } 161 162 /** 163 * Stores the given throwable and rethrows it. It will be rethrown as is if it is an {@code 164 * IOException}, {@code RuntimeException}, {@code Error} or a checked exception of either of the 165 * given types. Otherwise, it will be rethrown wrapped in a {@code RuntimeException}. <b>Note:</b> 166 * Be sure to declare all of the checked exception types your try block can throw when calling an 167 * overload of this method so as to avoid losing the original exception type. 168 * 169 * <p>This method always throws, and as such should be called as {@code throw closer.rethrow(e, 170 * ...);} to ensure the compiler knows that it will throw. 171 * 172 * @return this method does not return; it always throws 173 * @throws IOException when the given throwable is an IOException 174 * @throws X1 when the given throwable is of the declared type X1 175 * @throws X2 when the given throwable is of the declared type X2 176 */ 177 public <X1 extends Exception, X2 extends Exception> RuntimeException rethrow( 178 Throwable e, Class<X1> declaredType1, Class<X2> declaredType2) throws IOException, X1, X2 { 179 checkNotNull(e); 180 thrown = e; 181 throwIfInstanceOf(e, IOException.class); 182 throwIfInstanceOf(e, declaredType1); 183 throwIfInstanceOf(e, declaredType2); 184 throwIfUnchecked(e); 185 throw new RuntimeException(e); 186 } 187 188 /** 189 * Closes all {@code Closeable} instances that have been added to this {@code Closer}. If an 190 * exception was thrown in the try block and passed to one of the {@code exceptionThrown} methods, 191 * any exceptions thrown when attempting to close a closeable will be suppressed. Otherwise, the 192 * <i>first</i> exception to be thrown from an attempt to close a closeable will be thrown and any 193 * additional exceptions that are thrown after that will be suppressed. 194 */ 195 @Override 196 public void close() throws IOException { 197 Throwable throwable = thrown; 198 199 // close closeables in LIFO order 200 while (!stack.isEmpty()) { 201 Closeable closeable = stack.removeFirst(); 202 try { 203 closeable.close(); 204 } catch (Throwable e) { 205 if (throwable == null) { 206 throwable = e; 207 } else { 208 suppressor.suppress(closeable, throwable, e); 209 } 210 } 211 } 212 213 if (thrown == null && throwable != null) { 214 throwIfInstanceOf(throwable, IOException.class); 215 throwIfUnchecked(throwable); 216 throw new AssertionError(throwable); // not possible 217 } 218 } 219 220 /** Suppression strategy interface. */ 221 @VisibleForTesting 222 interface Suppressor { 223 /** 224 * Suppresses the given exception ({@code suppressed}) which was thrown when attempting to close 225 * the given closeable. {@code thrown} is the exception that is actually being thrown from the 226 * method. Implementations of this method should not throw under any circumstances. 227 */ 228 void suppress(Closeable closeable, Throwable thrown, Throwable suppressed); 229 } 230 231 /** 232 * Suppresses exceptions by adding them to the exception that will be thrown using the 233 * addSuppressed(Throwable) mechanism. 234 */ 235 private static final Suppressor SUPPRESSING_SUPPRESSOR = 236 (closeable, thrown, suppressed) -> { 237 // ensure no exceptions from addSuppressed 238 if (thrown == suppressed) { 239 return; 240 } 241 try { 242 thrown.addSuppressed(suppressed); 243 } catch (Throwable e) { 244 /* 245 * A Throwable is very unlikely, but we really don't want to throw from a Suppressor, so 246 * we catch everything. (Any Exception is either a RuntimeException or 247 * sneaky checked exception.) With no better options, we log anything to the same 248 * place as Closeables logs. 249 */ 250 Closeables.logger.log( 251 Level.WARNING, "Suppressing exception thrown when closing " + closeable, suppressed); 252 } 253 }; 254}