/** 
 * 
 * Copyright 2004 Protique Ltd
 * 
 * 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 org.codehaus.activemq.message.util;
import java.util.Iterator;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.activemq.capacity.BasicCapacityMonitor;
import org.codehaus.activemq.message.Packet;
import EDU.oswego.cs.dl.util.concurrent.ConcurrentHashMap;
import EDU.oswego.cs.dl.util.concurrent.SynchronizedLong;

/**
 * A factory manager for MemoryBoundedQueue and also ensures that the maximum memory used by all active
 * MemoryBoundedQueues cewated by this instance stays within the memory usage bounds set.
 * 
 * @version $Revision: 1.1 $
 */
public class MemoryBoundedQueueManager extends BasicCapacityMonitor {
    private static final int OBJECT_OVERHEAD = 50;
    SynchronizedLong totalMemoryUsedSize = new SynchronizedLong(0);
    private ConcurrentHashMap activeQueues = new ConcurrentHashMap();
    private static final Log log = LogFactory.getLog(MemoryBoundedQueueManager.class);

    /**
     * @param name
     * @param maxSize
     */
    public MemoryBoundedQueueManager(String name, long maxSize) {
        super(name, maxSize);
    }

    /**
     * retrieve a named MemoryBoundedQueue or creates one if not found
     * 
     * @param name
     * @return an named instance of a MemoryBoundedQueue
     */
    public MemoryBoundedQueue getMemoryBoundedQueue(String name) {
        MemoryBoundedQueue result = (MemoryBoundedQueue) activeQueues.get(name);
        if (result == null) {
            result = new MemoryBoundedQueue(name, this);
            activeQueues.put(name, result);
        }
        return result;
    }

    /**
     * close this queue manager and all associated MemoryBoundedQueues
     */
    public void close() {
        for (Iterator i = activeQueues.values().iterator();i.hasNext();) {
            MemoryBoundedQueue mbq = (MemoryBoundedQueue) i.next();
            mbq.close();
        }
        activeQueues.clear();
    }

    /**
     * @return the calculated total memory usage assocated with all it's queues
     */
    public long getTotalMemoryUsedSize() {
        return totalMemoryUsedSize.get();
    }

    /**
     * @return true if this MemoryBoundedQueueManager has reached it's predefined limit
     */
    public boolean isFull() {
        boolean result = totalMemoryUsedSize.get() >= super.getValueLimit();
        return result;
    }

    int incrementMemoryUsed(Packet obj) {
        int size = OBJECT_OVERHEAD;
        if (obj != null) {
            if (obj.getMemoryUsageReferenceCount() == 0) {
                size += obj.getMemoryUsage();
            }
            obj.incrementMemoryReferenceCount();
        }
        totalMemoryUsedSize.add(size);
        super.setCurrentValue(totalMemoryUsedSize.get());
        return size;
    }

    int decrementMemoryUsed(Packet obj) {
        int size = OBJECT_OVERHEAD;
        if (obj != null) {
            obj.decrementMemoryReferenceCount();
            if (obj.getMemoryUsageReferenceCount() == 0) {
                size += obj.getMemoryUsage();
            }
        }
        totalMemoryUsedSize.subtract(size);
        super.setCurrentValue(totalMemoryUsedSize.get());
        return size;
    }

    protected void finalize() {
        close();
    }

    void removeMemoryBoundedQueue(String name) {
        activeQueues.remove(name);
    }
}
