001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache license, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the license for the specific language governing permissions and
015 * limitations under the license.
016 */
017
018package org.apache.logging.log4j.core.util;
019
020/**
021 * Helper class for closing resources.
022 */
023public final class Closer {
024
025    private Closer() {
026    }
027
028    /**
029     * Closes an AutoCloseable or ignores if {@code null}.
030     *
031     * @param closeable the resource to close; may be null
032     * @throws Exception if the resource cannot be closed
033     * @since 2.8
034     */
035    public static void close(final AutoCloseable closeable) throws Exception {
036        if (closeable != null) {
037            closeable.close();
038        }
039    }
040
041    /**
042     * Closes an AutoCloseable and returns {@code true} if it closed without exception.
043     *
044     * @param closeable the resource to close; may be null
045     * @return true if resource was closed successfully, or false if an exception was thrown
046     */
047    public static boolean closeSilently(final AutoCloseable closeable) {
048        try {
049            close(closeable);
050            return true;
051        } catch (final Exception ignored) {
052            return false;
053        }
054    }
055
056}