View Javadoc
1   /*
2    * Copyright (C) 2012 The Guava Authors
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5    * in compliance with the License. You may obtain a copy of the License at
6    *
7    * http://www.apache.org/licenses/LICENSE-2.0
8    *
9    * Unless required by applicable law or agreed to in writing, software distributed under the License
10   * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11   * or implied. See the License for the specific language governing permissions and limitations under
12   * the License.
13   */
14  
15  package com.google.common.io;
16  
17  import static com.google.common.base.Preconditions.checkNotNull;
18  
19  import com.google.common.annotations.Beta;
20  import com.google.common.annotations.GwtIncompatible;
21  import com.google.common.annotations.VisibleForTesting;
22  import com.google.common.base.Throwables;
23  import com.google.errorprone.annotations.CanIgnoreReturnValue;
24  import java.io.Closeable;
25  import java.io.IOException;
26  import java.lang.reflect.Method;
27  import java.util.ArrayDeque;
28  import java.util.Deque;
29  import java.util.logging.Level;
30  import javax.annotation.Nullable;
31  
32  /**
33   * A {@link Closeable} that collects {@code Closeable} resources and closes them all when it is
34   * {@linkplain #close closed}. This is intended to approximately emulate the behavior of Java 7's
35   * <a href="http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html"
36   * >try-with-resources</a> statement in JDK6-compatible code. Running on Java 7, code using this
37   * should be approximately equivalent in behavior to the same code written with try-with-resources.
38   * Running on Java 6, exceptions that cannot be thrown must be logged rather than being added to the
39   * thrown exception as a suppressed exception.
40   *
41   * <p>This class is intended to be used in the following pattern:
42   *
43   * <pre>   {@code
44   *   Closer closer = Closer.create();
45   *   try {
46   *     InputStream in = closer.register(openInputStream());
47   *     OutputStream out = closer.register(openOutputStream());
48   *     // do stuff
49   *   } catch (Throwable e) {
50   *     // ensure that any checked exception types other than IOException that could be thrown are
51   *     // provided here, e.g. throw closer.rethrow(e, CheckedException.class);
52   *     throw closer.rethrow(e);
53   *   } finally {
54   *     closer.close();
55   *   }}</pre>
56   *
57   * <p>Note that this try-catch-finally block is not equivalent to a try-catch-finally block using
58   * try-with-resources. To get the equivalent of that, you must wrap the above code in <i>another</i>
59   * try block in order to catch any exception that may be thrown (including from the call to
60   * {@code close()}).
61   *
62   * <p>This pattern ensures the following:
63   *
64   * <ul>
65   * <li>Each {@code Closeable} resource that is successfully registered will be closed later.
66   * <li>If a {@code Throwable} is thrown in the try block, no exceptions that occur when attempting
67   *     to close resources will be thrown from the finally block. The throwable from the try block
68   *     will be thrown.
69   * <li>If no exceptions or errors were thrown in the try block, the <i>first</i> exception thrown by
70   *     an attempt to close a resource will be thrown.
71   * <li>Any exception caught when attempting to close a resource that is <i>not</i> thrown (because
72   *     another exception is already being thrown) is <i>suppressed</i>.
73   * </ul>
74   *
75   * <p>An exception that is suppressed is not thrown. The method of suppression used depends on the
76   * version of Java the code is running on:
77   *
78   * <ul>
79   * <li><b>Java 7+:</b> Exceptions are suppressed by adding them to the exception that <i>will</i> be
80   *     thrown using {@code Throwable.addSuppressed(Throwable)}.
81   * <li><b>Java 6:</b> Exceptions are suppressed by logging them instead.
82   * </ul>
83   *
84   * @author Colin Decker
85   * @since 14.0
86   */
87  // Coffee's for {@link Closer closers} only.
88  @Beta
89  @GwtIncompatible
90  public final class Closer implements Closeable {
91  
92    /**
93     * The suppressor implementation to use for the current Java version.
94     */
95    private static final Suppressor SUPPRESSOR =
96        SuppressingSuppressor.isAvailable()
97            ? SuppressingSuppressor.INSTANCE
98            : LoggingSuppressor.INSTANCE;
99  
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 }