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 */
017package org.apache.activemq.usage;
018
019
020import org.apache.activemq.store.PListStore;
021
022/**
023 * Used to keep track of how much of something is being used so that a
024 * productive working set usage can be controlled. Main use case is manage
025 * memory usage.
026 *
027 * @org.apache.xbean.XBean
028 *
029 */
030public class TempUsage extends PercentLimitUsage<TempUsage> {
031
032    private PListStore store;
033
034    public TempUsage() {
035        super(null, null, 1.0f);
036    }
037
038    public TempUsage(String name, PListStore store) {
039        super(null, name, 1.0f);
040        this.store = store;
041        updateLimitBasedOnPercent();
042    }
043
044    public TempUsage(TempUsage parent, String name) {
045        super(parent, name, 1.0f);
046        this.store = parent.store;
047        updateLimitBasedOnPercent();
048    }
049
050    @Override
051    public int getPercentUsage() {
052        if (store != null) {
053            usageLock.writeLock().lock();
054            try {
055                percentUsage = caclPercentUsage();
056            } finally {
057                usageLock.writeLock().unlock();
058            }
059        }
060        return super.getPercentUsage();
061    }
062
063    @Override
064    protected long retrieveUsage() {
065        if (store == null) {
066            return 0;
067        }
068        return store.size();
069    }
070
071    public PListStore getStore() {
072        return store;
073    }
074
075    public void setStore(PListStore store) {
076        this.store = store;
077        if (percentLimit > 0 && store != null) {
078            //will trigger onLimitChange
079            updateLimitBasedOnPercent();
080        } else {
081            onLimitChange();
082        }
083    }
084
085    @Override
086    protected void updateLimitBasedOnPercent() {
087        usageLock.writeLock().lock();
088        try {
089            percentLimitFromFile(store != null ? store.getDirectory() : null);
090        } finally {
091            usageLock.writeLock().unlock();
092        }
093    }
094
095}