Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright (C) 2012 The Guava Authors
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 package com.google.common.io;
 
 import static com.google.common.base.Preconditions.checkNotNull;
 
 
 
A java.io.Closeable that collects Closeable resources and closes them all when it is closed. This is intended to approximately emulate the behavior of Java 7's try-with-resources statement in JDK6-compatible code. Running on Java 7, code using this should be approximately equivalent in behavior to the same code written with try-with-resources. Running on Java 6, exceptions that cannot be thrown must be logged rather than being added to the thrown exception as a suppressed exception.

This class is intended to be used in the following pattern:

   Closer closer = Closer.create();
   try {
     InputStream in = closer.register(openInputStream());
     OutputStream out = closer.register(openOutputStream());
     // do stuff
    catch (Throwable e) {
     // ensure that any checked exception types other than IOException that could be thrown are
     // provided here, e.g. throw closer.rethrow(e, CheckedException.class);
     throw closer.rethrow(e);
   } finally {
     closer.close();
   }}

Note that this try-catch-finally block is not equivalent to a try-catch-finally block using try-with-resources. To get the equivalent of that, you must wrap the above code in another try block in order to catch any exception that may be thrown (including from the call to close()).

This pattern ensures the following:

  • Each Closeable resource that is successfully registered will be closed later.
  • If a Throwable is thrown in the try block, no exceptions that occur when attempting to close resources will be thrown from the finally block. The throwable from the try block will be thrown.
  • If no exceptions or errors were thrown in the try block, the first exception thrown by an attempt to close a resource will be thrown.
  • Any exception caught when attempting to close a resource that is not thrown (because another exception is already being thrown) is suppressed.

An exception that is suppressed is not thrown. The method of suppression used depends on the version of Java the code is running on:

  • Java 7+: Exceptions are suppressed by adding them to the exception that will be thrown using Throwable.addSuppressed(Throwable).
  • Java 6: Exceptions are suppressed by logging them instead.

Author(s):
Colin Decker
Since:
14.0
 
 // Coffee's for {@link Closer closers} only.
 public final class Closer implements Closeable {

  
The suppressor implementation to use for the current Java version.
 
   private static final Suppressor SUPPRESSOR = SuppressingSuppressor.isAvailable()
       : .;

  
Creates a new Closer.
  public static Closer create() {
    return new Closer();
  }
  // only need space for 2 elements in most cases, so try to use the smallest array possible
  private final Deque<Closeablestack = new ArrayDeque<Closeable>(4);
  private Throwable thrown;
  @VisibleForTesting Closer(Suppressor suppressor) {
    this. = checkNotNull(suppressor); // checkNotNull to satisfy null tests
  }

  
Registers the given closeable to be closed when this Closer is closed.

Returns:
the given closeable
  // close. this word no longer has any meaning to me.
  public <C extends Closeable> C register(@Nullable C closeable) {
    if (closeable != null) {
      .addFirst(closeable);
    }
    return closeable;
  }

  
Stores the given throwable and rethrows it. It will be rethrown as is if it is an IOException, RuntimeException or Error. Otherwise, it will be rethrown wrapped in a RuntimeException. Note: Be sure to declare all of the checked exception types your try block can throw when calling an overload of this method so as to avoid losing the original exception type.

This method always throws, and as such should be called as throw closer.rethrow(e); to ensure the compiler knows that it will throw.

Returns:
this method does not return; it always throws
Throws:
java.io.IOException when the given throwable is an IOException
  public RuntimeException rethrow(Throwable ethrows IOException {
    checkNotNull(e);
     = e;
    Throwables.propagateIfPossible(eIOException.class);
    throw new RuntimeException(e);
  }

  
Stores the given throwable and rethrows it. It will be rethrown as is if it is an IOException, RuntimeException, Error or a checked exception of the given type. Otherwise, it will be rethrown wrapped in a RuntimeException. Note: Be sure to declare all of the checked exception types your try block can throw when calling an overload of this method so as to avoid losing the original exception type.

This method always throws, and as such should be called as throw closer.rethrow(e, ...); to ensure the compiler knows that it will throw.

Returns:
this method does not return; it always throws
Throws:
java.io.IOException when the given throwable is an IOException
X when the given throwable is of the declared type X
  public <X extends ExceptionRuntimeException rethrow(Throwable e,
      Class<X> declaredTypethrows IOException, X {
    checkNotNull(e);
     = e;
    Throwables.propagateIfPossible(eIOException.class);
    Throwables.propagateIfPossible(edeclaredType);
    throw new RuntimeException(e);
  }

  
Stores the given throwable and rethrows it. It will be rethrown as is if it is an IOException, RuntimeException, Error or a checked exception of either of the given types. Otherwise, it will be rethrown wrapped in a RuntimeException. Note: Be sure to declare all of the checked exception types your try block can throw when calling an overload of this method so as to avoid losing the original exception type.

This method always throws, and as such should be called as throw closer.rethrow(e, ...); to ensure the compiler knows that it will throw.

Returns:
this method does not return; it always throws
Throws:
java.io.IOException when the given throwable is an IOException
X1 when the given throwable is of the declared type X1
X2 when the given throwable is of the declared type X2
  public <X1 extends Exception, X2 extends ExceptionRuntimeException rethrow(
      Throwable eClass<X1> declaredType1Class<X2> declaredType2throws IOException, X1, X2 {
    checkNotNull(e);
     = e;
    Throwables.propagateIfPossible(eIOException.class);
    Throwables.propagateIfPossible(edeclaredType1declaredType2);
    throw new RuntimeException(e);
  }

  
Closes all Closeable instances that have been added to this Closer. If an exception was thrown in the try block and passed to one of the exceptionThrown methods, any exceptions thrown when attempting to close a closeable will be suppressed. Otherwise, the first exception to be thrown from an attempt to close a closeable will be thrown and any additional exceptions that are thrown after that will be suppressed.
  public void close() throws IOException {
    Throwable throwable = ;
    // close closeables in LIFO order
    while (!.isEmpty()) {
      Closeable closeable = .removeFirst();
      try {
        closeable.close();
      } catch (Throwable e) {
        if (throwable == null) {
          throwable = e;
        } else {
          .suppress(closeablethrowablee);
        }
      }
    }
    if ( == null && throwable != null) {
      Throwables.propagateIfPossible(throwableIOException.class);
      throw new AssertionError(throwable); // not possible
    }
  }

  
Suppression strategy interface.
  @VisibleForTesting interface Suppressor {
    
Suppresses the given exception (suppressed) which was thrown when attempting to close the given closeable. thrown is the exception that is actually being thrown from the method. Implementations of this method should not throw under any circumstances.
    void suppress(Closeable closeableThrowable thrownThrowable suppressed);
  }

  
Suppresses exceptions by logging them.
  @VisibleForTesting static final class LoggingSuppressor implements Suppressor {
    static final LoggingSuppressor INSTANCE = new LoggingSuppressor();
    @Override
    public void suppress(Closeable closeableThrowable thrownThrowable suppressed) {
      // log to the same place as Closeables
          "Suppressing exception thrown when closing " + closeablesuppressed);
    }
  }

  
Suppresses exceptions by adding them to the exception that will be thrown using JDK7's addSuppressed(Throwable) mechanism.
  @VisibleForTesting static final class SuppressingSuppressor implements Suppressor {
    static final SuppressingSuppressor INSTANCE = new SuppressingSuppressor();
    static boolean isAvailable() {
      return  != null;
    }
    static final Method addSuppressed = getAddSuppressed();
    private static Method getAddSuppressed() {
      try {
        return Throwable.class.getMethod("addSuppressed"Throwable.class);
      } catch (Throwable e) {
        return null;
      }
    }
    @Override
    public void suppress(Closeable closeableThrowable thrownThrowable suppressed) {
      // ensure no exceptions from addSuppressed
      if (thrown == suppressed) {
        return;
      }
      try {
        .invoke(thrownsuppressed);
      } catch (Throwable e) {
        // if, somehow, IllegalAccessException or another exception is thrown, fall back to logging
        ..suppress(closeablethrownsuppressed);
      }
    }
  }
New to GrepCode? Check out our FAQ X