This is an automated email from the ASF dual-hosted git repository.

garydgregory pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-lang.git


The following commit(s) were added to refs/heads/master by this push:
     new 990e1f62b Add AutoCloseables (#1643)
990e1f62b is described below

commit 990e1f62bd3ead86785bdca2312ed6fe8ed7782c
Author: Gary Gregory <[email protected]>
AuthorDate: Sun May 10 09:07:13 2026 -0400

    Add AutoCloseables (#1643)
---
 .../org/apache/commons/lang3/AutoCloseables.java   | 146 +++++++++++++++
 .../apache/commons/lang3/AutoCloseablesTest.java   | 197 +++++++++++++++++++++
 2 files changed, 343 insertions(+)

diff --git a/src/main/java/org/apache/commons/lang3/AutoCloseables.java 
b/src/main/java/org/apache/commons/lang3/AutoCloseables.java
new file mode 100644
index 000000000..e4c574aa7
--- /dev/null
+++ b/src/main/java/org/apache/commons/lang3/AutoCloseables.java
@@ -0,0 +1,146 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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
+ *
+ *      https://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 org.apache.commons.lang3;
+
+import java.io.Closeable;
+import java.util.function.Consumer;
+
+import org.apache.commons.lang3.function.Consumers;
+import org.apache.commons.lang3.function.FailableConsumer;
+
+/**
+ * Static operations on {@link AutoCloseable}.
+ * <p>
+ * For {@link Closeable}-specific methods, see Apache Commons IO's
+ * <a 
href="https://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/IOUtils.html";>IOUtils</a>.
+ * </p>
+ *
+ * @since 3.21.0
+ */
+public class AutoCloseables {
+
+    /**
+     * Closes the given {@link AutoCloseable} as a null-safe operation.
+     *
+     * @param closeable The resource to close, may be null.
+     * @throws Exception if an error occurs.
+     */
+    public static void close(final AutoCloseable closeable) throws Exception {
+        if (closeable != null) {
+            closeable.close();
+        }
+    }
+
+    /**
+     * Closes the given {@link AutoCloseable} as a null-safe operation.
+     *
+     * @param closeable The resource to close, may be null.
+     * @param consumer  Consume the Exception thrown by {@link 
AutoCloseable#close()}.
+     * @throws Exception As thrown by the consumer.
+     */
+    public static void close(final AutoCloseable closeable, final 
FailableConsumer<Exception, Exception> consumer) throws Exception {
+        if (closeable != null) {
+            try {
+                closeable.close();
+            } catch (final Exception e) {
+                FailableConsumer.accept(consumer, e);
+            }
+        }
+    }
+
+    /**
+     * Closes an {@link AutoCloseable}, never throwing an {@link Exception}.
+     * <p>
+     * Equivalent to {@link AutoCloseable#close()}, except any exceptions will 
be ignored.
+     * </p>
+     *
+     * @param closeable the objects to close, may be null or already closed.
+     * @see Throwable#addSuppressed(Throwable)
+     */
+    public static void closeQuietly(final AutoCloseable closeable) {
+        closeQuietly(closeable, (Consumer<Exception>) null);
+    }
+
+    /**
+     * Closes the given {@link AutoCloseable} as a null-safe operation while 
consuming Exception by the given {@code consumer}.
+     *
+     * @param closeable The resource to close, may be null.
+     * @param consumer  Consumes the Exception thrown by {@link 
AutoCloseable#close()}.
+     */
+    public static void closeQuietly(final AutoCloseable closeable, final 
Consumer<Exception> consumer) {
+        if (closeable != null) {
+            try {
+                closeable.close();
+            } catch (final Exception e) {
+                Consumers.accept(consumer, e);
+            }
+        }
+    }
+
+    /**
+     * Closes an iterable of {@link AutoCloseable}, never throwing an {@link 
Exception}.
+     * <p>
+     * Equivalent calling {@link AutoCloseable#close()} on each element, 
except any exceptions will be ignored.
+     * </p>
+     *
+     * @param closeables the objects to close, may be null or already closed.
+     * @see #closeQuietly(AutoCloseable)
+     */
+    public static void closeQuietly(final Iterable<AutoCloseable> closeables) {
+        if (closeables != null) {
+            closeables.forEach(AutoCloseables::closeQuietly);
+        }
+    }
+
+    /**
+     * Closes a {@link Closeable} unconditionally and adds any exception 
thrown by the {@code close()} to the given Throwable.
+     * <p>
+     * For example:
+     * </p>
+     *
+     * <pre>
+     * AutoCloseable autoCloseable = ...;
+     * try {
+     *     // process autoCloseable.
+     * } catch (Exception e) {
+     *     // Handle exception.
+     *     throw AutoCloseables.closeQuietlySuppress(autoCloseable, e);
+     * }
+     * </pre>
+     * <p>
+     * Also consider using a try-with-resources statement where appropriate.
+     * </p>
+     *
+     * @param <T>       The Throwable type.
+     * @param closeable The object to close, may be null or already closed.
+     * @param throwable Add the exception throw by the closeable to the given 
Throwable.
+     * @return The given Throwable.
+     * @see Throwable#addSuppressed(Throwable)
+     */
+    public static <T extends Throwable> T closeQuietlySuppress(final Closeable 
closeable, final T throwable) {
+        closeQuietly(closeable, throwable::addSuppressed);
+        return throwable;
+    }
+
+    /**
+     * No instances needed.
+     */
+    private AutoCloseables() {
+        // empty
+    }
+}
diff --git a/src/test/java/org/apache/commons/lang3/AutoCloseablesTest.java 
b/src/test/java/org/apache/commons/lang3/AutoCloseablesTest.java
new file mode 100644
index 000000000..fad140b61
--- /dev/null
+++ b/src/test/java/org/apache/commons/lang3/AutoCloseablesTest.java
@@ -0,0 +1,197 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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
+ *
+ *      https://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 org.apache.commons.lang3;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
+
+import org.junit.jupiter.api.Test;
+
+/**
+ * Tests {@link AutoCloseables}.
+ */
+class AutoCloseablesTest extends AbstractLangTest {
+
+    /** An AutoCloseable that always throws on close(). */
+    private static class ThrowingCloseable implements Closeable {
+
+        private final IOException exception;
+
+        ThrowingCloseable(final IOException exception) {
+            this.exception = exception;
+        }
+
+        @Override
+        public void close() throws IOException {
+            throw exception;
+        }
+    }
+
+    /** An AutoCloseable that tracks whether close() was called. */
+    private static class TrackingCloseable implements Closeable {
+
+        private final AtomicBoolean closed = new AtomicBoolean();
+
+        @Override
+        public void close() {
+            closed.set(true);
+        }
+
+        boolean isClosed() {
+            return closed.get();
+        }
+    }
+
+    @Test
+    void testClose_closesResource() throws Exception {
+        final TrackingCloseable tc = new TrackingCloseable();
+        AutoCloseables.close(tc);
+        assertTrue(tc.isClosed(), "Expected resource to be closed");
+    }
+
+    @Test
+    void testClose_null_doesNotThrow() throws Exception {
+        AutoCloseables.close((AutoCloseable) null);
+    }
+
+    @Test
+    void testClose_propagatesException() {
+        final IOException cause = new IOException("boom");
+        final ThrowingCloseable tc = new ThrowingCloseable(cause);
+        final Exception thrown = assertThrows(Exception.class, () -> 
AutoCloseables.close(tc));
+        assertEquals(cause, thrown);
+    }
+
+    @Test
+    void testClose_withConsumer_closesResource() throws Exception {
+        final TrackingCloseable tc = new TrackingCloseable();
+        AutoCloseables.close(tc, null);
+        assertTrue(tc.isClosed(), "Expected resource to be closed");
+    }
+
+    @Test
+    void testClose_withConsumer_exceptionDeliveredToConsumer() throws 
Exception {
+        final IOException cause = new IOException("boom");
+        final ThrowingCloseable tc = new ThrowingCloseable(cause);
+        final AtomicReference<Exception> received = new AtomicReference<>();
+        AutoCloseables.close(tc, received::set);
+        assertEquals(cause, received.get(), "Consumer should have received the 
exception");
+    }
+
+    @Test
+    void testClose_withConsumer_null_doesNotThrow() throws Exception {
+        AutoCloseables.close(null, null);
+    }
+
+    @Test
+    void testCloseQuietly_closesResource() {
+        final TrackingCloseable tc = new TrackingCloseable();
+        AutoCloseables.closeQuietly(tc);
+        assertTrue(tc.isClosed(), "Expected resource to be closed");
+    }
+
+    @Test
+    void testCloseQuietly_iterable_closesAllResources() {
+        final TrackingCloseable tc1 = new TrackingCloseable();
+        final TrackingCloseable tc2 = new TrackingCloseable();
+        AutoCloseables.closeQuietly(Arrays.asList(tc1, tc2));
+        assertTrue(tc1.isClosed(), "Expected first resource to be closed");
+        assertTrue(tc2.isClosed(), "Expected second resource to be closed");
+    }
+
+    @Test
+    void testCloseQuietly_iterable_null_doesNotThrow() {
+        AutoCloseables.closeQuietly((Iterable<AutoCloseable>) null);
+    }
+
+    @Test
+    void testCloseQuietly_iterable_swallowsExceptions() {
+        final ThrowingCloseable tc1 = new ThrowingCloseable(new 
IOException("first"));
+        final ThrowingCloseable tc2 = new ThrowingCloseable(new 
IOException("second"));
+        AutoCloseables.closeQuietly(Arrays.asList(tc1, tc2));
+    }
+
+    @Test
+    void testCloseQuietly_null_doesNotThrow() {
+        AutoCloseables.closeQuietly((AutoCloseable) null);
+    }
+
+    @Test
+    void testCloseQuietly_swallowsException() {
+        final ThrowingCloseable tc = new ThrowingCloseable(new 
IOException("ignored"));
+        AutoCloseables.closeQuietly(tc);
+    }
+
+    @Test
+    void testCloseQuietly_withConsumer_exceptionDeliveredToConsumer() {
+        final IOException cause = new IOException("boom");
+        final ThrowingCloseable tc = new ThrowingCloseable(cause);
+        final AtomicReference<Exception> received = new AtomicReference<>();
+        AutoCloseables.closeQuietly(tc, received::set);
+        assertEquals(cause, received.get(), "Consumer should have received the 
exception");
+    }
+
+    @Test
+    void testCloseQuietly_withConsumer_null_doesNotThrow() {
+        AutoCloseables.closeQuietly(null, 
(java.util.function.Consumer<Exception>) null);
+    }
+
+    @Test
+    void testCloseQuietly_withNullConsumer_swallowsException() {
+        final ThrowingCloseable tc = new ThrowingCloseable(new 
IOException("ignored"));
+        AutoCloseables.closeQuietly(tc, 
(java.util.function.Consumer<Exception>) null);
+    }
+
+    @Test
+    void testCloseQuietlySuppress_addsSuppressedException() {
+        final IOException closeException = new IOException("close failure");
+        final ThrowingCloseable tc = new ThrowingCloseable(closeException);
+        final RuntimeException primary = new RuntimeException("primary");
+        final RuntimeException result = 
AutoCloseables.closeQuietlySuppress(tc, primary);
+        assertEquals(primary, result);
+        assertNotNull(result.getSuppressed());
+        assertEquals(1, result.getSuppressed().length);
+        assertEquals(closeException, result.getSuppressed()[0]);
+    }
+
+    @Test
+    void testCloseQuietlySuppress_noException_returnsThrowable() throws 
Exception {
+        final TrackingCloseable tc = new TrackingCloseable();
+        final RuntimeException primary = new RuntimeException("primary");
+        final RuntimeException result = 
AutoCloseables.closeQuietlySuppress(tc, primary);
+        assertEquals(primary, result);
+        assertTrue(tc.isClosed());
+        assertEquals(0, result.getSuppressed().length, "No suppressed 
exceptions expected");
+    }
+
+    @Test
+    void testCloseQuietlySuppress_null_returnsThrowable() {
+        final RuntimeException primary = new RuntimeException("primary");
+        final RuntimeException result = 
AutoCloseables.closeQuietlySuppress(null, primary);
+        assertEquals(primary, result, "Should return the given throwable 
unchanged");
+        assertEquals(0, result.getSuppressed().length, "No suppressed 
exceptions expected");
+    }
+}

Reply via email to