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    package org.apache.logging.log4j.core.appender;
018    
019    import org.apache.logging.log4j.Logger;
020    import org.apache.logging.log4j.status.StatusLogger;
021    
022    import java.util.HashMap;
023    import java.util.Map;
024    import java.util.concurrent.locks.Lock;
025    import java.util.concurrent.locks.ReentrantLock;
026    
027    /**
028     * Abstract base class used to register managers.
029     */
030    public abstract class AbstractManager {
031    
032        /**
033         * Allow subclasses access to the status logger without creating another instance.
034         */
035        protected static final Logger LOGGER = StatusLogger.getLogger();
036    
037        // Need to lock that map instead of using a ConcurrentMap due to stop removing the
038        // manager from the map and closing the stream, requiring the whole stop method to be locked.
039        private static final Map<String, AbstractManager> map = new HashMap<String, AbstractManager>();
040    
041        private static final Lock lock = new ReentrantLock();
042    
043        /**
044         * Number of Appenders using this manager.
045         */
046        protected int count;
047    
048        private final String name;
049    
050        protected AbstractManager(String name) {
051            this.name = name;
052            LOGGER.debug("Starting {} {}", this.getClass().getSimpleName(), name);
053        }
054    
055        /**
056         * Retrieves a Manager if it has been previously created or creates a new Manager.
057         * @param name The name of the Manager to retrieve.
058         * @param factory The Factory to use to create the Manager.
059         * @param data An Object that should be passed to the factory when creating the Manager.
060         * @param <M> The Type of the Manager to be created.
061         * @return A Manager with the specified name and type.
062         */
063        public static <M extends AbstractManager, T> M getManager(String name, ManagerFactory<M, T> factory, T data) {
064            lock.lock();
065            try {
066                M manager = (M) map.get(name);
067                if (manager == null) {
068                    manager = factory.createManager(name, data);
069                    if (manager == null) {
070                        throw new IllegalStateException("Unable to create a manager");
071                    }
072                    map.put(name, manager);
073                }
074                manager.count++;
075                return manager;
076            } finally {
077                lock.unlock();
078            }
079        }
080    
081        /**
082         * Determines if a Manager with the specified name exists.
083         * @param name The name of the Manager.
084         * @return True if the Manager exists, false otherwise.
085         */
086        public static boolean hasManager(String name) {
087            lock.lock();
088            try {
089                return map.containsKey(name);
090            } finally {
091                lock.unlock();
092            }
093        }
094    
095        /**
096         * May be overriden by Managers to perform processing while the Manager is being released and the
097         * lock is held.
098         */
099        protected void releaseSub() {
100        }
101    
102        protected int getCount() {
103            return count;
104        }
105    
106        /**
107         * Called to signify that this Manager is no longer required by an Appender.
108         */
109        public void release() {
110            lock.lock();
111            try {
112                --count;
113                if (count <= 0) {
114                    map.remove(name);
115                    LOGGER.debug("Shutting down {} {}", this.getClass().getSimpleName(), getName());
116                    releaseSub();
117                }
118            } finally {
119                lock.unlock();
120            }
121        }
122    
123        /**
124         * Returns the name of the Manager.
125         * @return The name of the Manager.
126         */
127        public String getName() {
128            return name;
129        }
130    }