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