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