Skip to content

Implement a closeAll utility to close multiple closeables #3470

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jul 14, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -912,32 +912,6 @@ public static void closeIterator(@Nonnull Iterator<?> iterator) {
}
}

/**
* A utility to close multiple {@link AutoCloseable} objects, preserving all the caught exceptions.
* The method would attempt to close all closeables in order, even if some failed.
* @param closeables the given sequence of {@link AutoCloseable}
* @throws CloseException in case any exception was caught during the process. The first exception will be added
* as a {@code cause}. In case more than one exception was caught, it will be added as Suppressed.
*/
@SuppressWarnings("PMD.CloseResource")
public static void closeAll(AutoCloseable... closeables) throws CloseException {
CloseException accumulatedException = null;
for (AutoCloseable closeable: closeables) {
try {
closeable.close();
} catch (Exception e) {
if (accumulatedException == null) {
accumulatedException = new CloseException(e);
} else {
accumulatedException.addSuppressed(e);
}
}
}
if (accumulatedException != null) {
throw accumulatedException;
}
}

/**
* This is supposed to replicate the semantics of {@link java.util.concurrent.CompletionStage#whenComplete(BiConsumer)}
* but to handle the case where the completion handler might itself contain async work.
Expand Down Expand Up @@ -1107,16 +1081,4 @@ private DeadlineExceededException(long deadlineTimeMillis) {
addLogInfo("deadlineTimeMillis", deadlineTimeMillis);
}
}

/**
* Exception thrown when the {@link #closeAll} method catches an exception.
* This exception will have the cause set to the first exception thrown during {@code closeAll} and any further
* exception thrown will be added as {@Suppressed}.
*/
@SuppressWarnings("serial")
public static class CloseException extends Exception {
public CloseException(final Throwable cause) {
super(cause);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/*
* CloseableUtils.java
*
* This source file is part of the FoundationDB open source project
*
* Copyright 2015-2025 Apple Inc. and the FoundationDB project 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.apple.foundationdb.util;

public class CloseableUtils {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Javadoc would be good, something short and sweet, like

Suggested change
public class CloseableUtils {
/**
* Utility methods to help interact with {@link AutoCloseable} things.
**/
public class CloseableUtils {

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also, an API annotation. INTERNAL I think.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done x2

/**
* A utility to close multiple {@link AutoCloseable} objects, preserving all the caught exceptions.
* The method would attempt to close all closeables in order, even if some failed.
* @param closeables the given sequence of {@link AutoCloseable}
* @throws CloseException in case any exception was caught during the process. The first exception will be added
* as a {@code cause}. In case more than one exception was caught, it will be added as Suppressed.
*/
@SuppressWarnings("PMD.CloseResource")
public static void closeAll(AutoCloseable... closeables) throws CloseException {
CloseException accumulatedException = null;
for (AutoCloseable closeable: closeables) {
try {
closeable.close();
} catch (Exception e) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since you are catch a generic exception, you are supposed to re-interrupt the current thread.

Also, probably worth a comment in the code here similar to the one on the PR explaining why we are converting it to a CloseException

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done. I think there could be no case of InterruptedException thrown from a close(), but it doesn't hurt to add a catch block.

if (accumulatedException == null) {
accumulatedException = new CloseException(e);
} else {
accumulatedException.addSuppressed(e);
}
}
}
if (accumulatedException != null) {
throw accumulatedException;
}
}

/**
* Exception thrown when the {@link CloseableUtils#closeAll} method catches an exception.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
* Exception thrown when the {@link CloseableUtils#closeAll} method catches an exception.
* Exception thrown when the {@link #closeAll} method catches an exception.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Exception moved to separate file.

* This exception will have the {@code cause} set to the first exception thrown during {@code closeAll} and any further
* exception thrown will be added as {@code Suppressed}.
*/
@SuppressWarnings("serial")
public static class CloseException extends Exception {
public CloseException(final Throwable cause) {
super(cause);
}
}

private CloseableUtils() {
// prevent constructor from being called
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@
import com.apple.test.ParameterizedTestUtils;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.hamcrest.Matcher;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
Expand Down Expand Up @@ -274,56 +273,8 @@ void swallowException() throws ExecutionException, InterruptedException {
throw new RuntimeException();
}).get();
}
}

@Test
void closeAllNoIssue() throws Exception {
SimpleCloseable c1 = new SimpleCloseable(false, null);
SimpleCloseable c2 = new SimpleCloseable(false, null);
SimpleCloseable c3 = new SimpleCloseable(false, null);

MoreAsyncUtil.closeAll(c1, c2, c3);

Assertions.assertTrue(c1.isClosed());
Assertions.assertTrue(c2.isClosed());
Assertions.assertTrue(c3.isClosed());
}

@Test
void closeAllFailed() throws Exception {
SimpleCloseable c1 = new SimpleCloseable(true, "c1");
SimpleCloseable c2 = new SimpleCloseable(true, "c2");
SimpleCloseable c3 = new SimpleCloseable(true, "c3");

final MoreAsyncUtil.CloseException exception = assertThrows(MoreAsyncUtil.CloseException.class, () -> MoreAsyncUtil.closeAll(c1, c2, c3));

Assertions.assertEquals("c1", exception.getCause().getMessage());
final Throwable[] suppressed = exception.getSuppressed();
Assertions.assertEquals(2, suppressed.length);
Assertions.assertEquals("c2", suppressed[0].getMessage());
Assertions.assertEquals("c3", suppressed[1].getMessage());

Assertions.assertTrue(c1.isClosed());
Assertions.assertTrue(c2.isClosed());
Assertions.assertTrue(c3.isClosed());
}

@Test
void closeSomeFailed() throws Exception {
SimpleCloseable c1 = new SimpleCloseable(true, "c1");
SimpleCloseable c2 = new SimpleCloseable(false, null);
SimpleCloseable c3 = new SimpleCloseable(true, "c3");

final MoreAsyncUtil.CloseException exception = assertThrows(MoreAsyncUtil.CloseException.class, () -> MoreAsyncUtil.closeAll(c1, c2, c3));

Assertions.assertEquals("c1", exception.getCause().getMessage());
final Throwable[] suppressed = exception.getSuppressed();
Assertions.assertEquals(1, suppressed.length);
Assertions.assertEquals("c3", suppressed[0].getMessage());

Assertions.assertTrue(c1.isClosed());
Assertions.assertTrue(c2.isClosed());
Assertions.assertTrue(c3.isClosed());
}

private static void assertSwallowedOrNot(final CompletableFuture<Void> completedExceptionally1, final RuntimeException runtimeException1) throws InterruptedException, ExecutionException {
Expand All @@ -344,27 +295,4 @@ private static Matcher<String> isCurrentThreadNameOr(@Nonnull String threadName)
private static Matcher<String> isCurrentThreadNameOr(@Nonnull Matcher<String> threadMatcher) {
return either(threadMatcher).or(equalTo(Thread.currentThread().getName()));
}

private class SimpleCloseable implements AutoCloseable {
private final boolean fail;
private final String message;
private boolean closed = false;

public SimpleCloseable(boolean fail, String message) {
this.fail = fail;
this.message = message;
}

@Override
public void close() {
closed = true;
if (fail) {
throw new RuntimeException(message);
}
}

public boolean isClosed() {
return closed;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
/*
* CloseableUtilsTest.java
*
* This source file is part of the FoundationDB open source project
*
* Copyright 2015-2025 Apple Inc. and the FoundationDB project 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.apple.foundationdb.util;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertThrows;

/**
* Tests for the {@link CloseableUtils} class.
*/
public class CloseableUtilsTest {

@Test
void closeAllNoIssue() throws Exception {
SimpleCloseable c1 = new SimpleCloseable(false, null);
SimpleCloseable c2 = new SimpleCloseable(false, null);
SimpleCloseable c3 = new SimpleCloseable(false, null);

CloseableUtils.closeAll(c1, c2, c3);

Assertions.assertTrue(c1.isClosed());
Assertions.assertTrue(c2.isClosed());
Assertions.assertTrue(c3.isClosed());
}

@Test
void closeAllFailed() throws Exception {
SimpleCloseable c1 = new SimpleCloseable(true, "c1");
SimpleCloseable c2 = new SimpleCloseable(true, "c2");
SimpleCloseable c3 = new SimpleCloseable(true, "c3");

final CloseableUtils.CloseException exception = assertThrows(CloseableUtils.CloseException.class, () -> CloseableUtils.closeAll(c1, c2, c3));

Assertions.assertEquals("c1", exception.getCause().getMessage());
final Throwable[] suppressed = exception.getSuppressed();
Assertions.assertEquals(2, suppressed.length);
Assertions.assertEquals("c2", suppressed[0].getMessage());
Assertions.assertEquals("c3", suppressed[1].getMessage());

Assertions.assertTrue(c1.isClosed());
Assertions.assertTrue(c2.isClosed());
Assertions.assertTrue(c3.isClosed());
}

@Test
void closeSomeFailed() throws Exception {
SimpleCloseable c1 = new SimpleCloseable(true, "c1");
SimpleCloseable c2 = new SimpleCloseable(false, null);
SimpleCloseable c3 = new SimpleCloseable(true, "c3");

final CloseableUtils.CloseException exception = assertThrows(CloseableUtils.CloseException.class, () -> CloseableUtils.closeAll(c1, c2, c3));

Assertions.assertEquals("c1", exception.getCause().getMessage());
final Throwable[] suppressed = exception.getSuppressed();
Assertions.assertEquals(1, suppressed.length);
Assertions.assertEquals("c3", suppressed[0].getMessage());

Assertions.assertTrue(c1.isClosed());
Assertions.assertTrue(c2.isClosed());
Assertions.assertTrue(c3.isClosed());
}

private class SimpleCloseable implements AutoCloseable {
private final boolean fail;
private final String message;
private boolean closed = false;

public SimpleCloseable(boolean fail, String message) {
this.fail = fail;
this.message = message;
}

@Override
public void close() {
closed = true;
if (fail) {
throw new RuntimeException(message);
}
}

public boolean isClosed() {
return closed;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
import com.apple.foundationdb.record.provider.foundationdb.FDBRecordStore;
import com.apple.foundationdb.record.provider.foundationdb.runners.FutureAutoClose;
import com.apple.foundationdb.record.provider.foundationdb.runners.TransactionalRunner;
import com.apple.foundationdb.util.CloseableUtils;
import com.google.common.annotations.VisibleForTesting;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Expand Down Expand Up @@ -149,13 +150,13 @@ public CompletableFuture<Void> iterateAll(final FDBRecordStore.Builder storeBuil
}

@Override
public void close() throws MoreAsyncUtil.CloseException {
public void close() throws CloseableUtils.CloseException {
if (closed) {
return;
}
closed = true;
// Ensure we call both close() methods, capturing all exceptions
MoreAsyncUtil.closeAll(futureManager, transactionalRunner);
CloseableUtils.closeAll(futureManager, transactionalRunner);
}

/**
Expand Down