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 020import org.apache.logging.log4j.status.StatusLogger; 021 022/** 023 * Closes resources. 024 */ 025public final class Closer { 026 027 private Closer() { 028 // empty 029 } 030 031 /** 032 * Closes an AutoCloseable or ignores if {@code null}. 033 * 034 * @param closeable the resource to close; may be null 035 * @return Whether the resource was closed. 036 * @throws Exception if the resource cannot be closed 037 * @since 2.8 038 * @since 2.11.2 returns a boolean instead of being a void return type. 039 */ 040 public static boolean close(final AutoCloseable closeable) throws Exception { 041 if (closeable != null) { 042 StatusLogger.getLogger().debug("Closing {} {}", closeable.getClass().getSimpleName(), closeable); 043 closeable.close(); 044 return true; 045 } 046 return false; 047 } 048 049 /** 050 * Closes an AutoCloseable and returns {@code true} if it closed without exception. 051 * 052 * @param closeable the resource to close; may be null 053 * @return true if resource was closed successfully, or false if an exception was thrown 054 */ 055 public static boolean closeSilently(final AutoCloseable closeable) { 056 try { 057 return close(closeable); 058 } catch (final Exception ignored) { 059 return false; 060 } 061 } 062 063}