Skip to content

Instantly share code, notes, and snippets.

@dain
Created September 16, 2014 19:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dain/b26e8878aabc6124c22a to your computer and use it in GitHub Desktop.
Save dain/b26e8878aabc6124c22a to your computer and use it in GitHub Desktop.
package io.airlift.testing;
import java.io.Closeable;
import java.io.IOException;
import static com.google.common.base.Preconditions.checkNotNull;
public final class Closeables
{
private Closeables()
{
}
public static void closeQuietly(Closeable... closeables)
{
if (closeables == null) {
return;
}
for (Closeable closeable : closeables) {
try {
if (closeable != null) {
closeable.close();
}
}
catch (IOException ignored) {
}
}
}
public static void closeAll(Closeable... closeables)
throws IOException
{
IOException rootCause = null;
for (Closeable closeable : closeables) {
try {
if (closeable != null) {
closeable.close();
}
}
catch (IOException e) {
if (rootCause == null) {
rootCause = e;
} else {
rootCause.addSuppressed(e);
}
} catch (RuntimeException e) {
if (rootCause == null) {
rootCause = new IOException(e);
} else {
rootCause.addSuppressed(e);
}
}
}
if (rootCause != null) {
throw rootCause;
}
}
public static void closeAllRuntimeException(Closeable... closeables)
{
RuntimeException rootCause = null;
for (Closeable closeable : closeables) {
try {
if (closeable != null) {
closeable.close();
}
}
catch (Throwable e) {
if (rootCause == null) {
rootCause = new RuntimeException(e);
} else {
rootCause.addSuppressed(e);
}
}
}
if (rootCause != null) {
throw rootCause;
}
}
public static <T extends Throwable> T closeAllSuppress(T rootCause, Closeable... closeables)
{
checkNotNull(rootCause, "rootCause is null");
if (closeables == null) {
return rootCause;
}
for (Closeable closeable : closeables) {
try {
if (closeable != null) {
closeable.close();
}
}
catch (Throwable e) {
rootCause.addSuppressed(e);
}
}
return rootCause;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment