⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 utilcache.java

📁 Sequoia ERP是一个真正的企业级开源ERP解决方案。它提供的模块包括:电子商务应用(e-commerce), POS系统(point of sales),知识管理,存货与仓库管理
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/* * $Id: UtilCache.java 5462 2005-08-05 18:35:48Z jonesde $ * *  Copyright (c) 2001-2005 The Open For Business Project - www.ofbiz.org * *  Permission is hereby granted, free of charge, to any person obtaining a *  copy of this software and associated documentation files (the "Software"), *  to deal in the Software without restriction, including without limitation *  the rights to use, copy, modify, merge, publish, distribute, sublicense, *  and/or sell copies of the Software, and to permit persons to whom the *  Software is furnished to do so, subject to the following conditions: * *  The above copyright notice and this permission notice shall be included *  in all copies or substantial portions of the Software. * *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS *  OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF *  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. *  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY *  CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT *  OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR *  THE USE OR OTHER DEALINGS IN THE SOFTWARE. */package org.ofbiz.base.util.cache;import java.io.Serializable;import java.util.Collection;import java.util.Iterator;import java.util.List;import java.util.Map;import java.util.MissingResourceException;import java.util.ResourceBundle;import java.util.Set;import java.util.WeakHashMap;import javolution.util.FastList;import javolution.util.FastMap;import javolution.util.FastSet;import org.ofbiz.base.util.Debug;import org.ofbiz.base.util.ObjectType;import org.ofbiz.base.util.UtilValidate;/** * Generalized caching utility. Provides a number of caching features: * <ul> *   <li>Limited or unlimited element capacity *   <li>If limited, removes elements with the LRU (Least Recently Used) algorithm *   <li>Keeps track of when each element was loaded into the cache *   <li>Using the expireTime can report whether a given element has expired *   <li>Counts misses and hits * </ul> * * @author     <a href="mailto:jonesde@ofbiz.org">David E. Jones</a> * @author     <a href="mailto:jaz@ofbiz.org">Andy Zeneski</a> * @version    $Rev: 5462 $ * @since      2.0 */public class UtilCache implements Serializable {    public static final String module = UtilCache.class.getName();        /** A static Map to keep track of all of the UtilCache instances. */    public static Map utilCacheTable = new WeakHashMap();    /** An index number appended to utilCacheTable names when there are conflicts. */    protected static Map defaultIndices = FastMap.newInstance();    /** The name of the UtilCache instance, is also the key for the instance in utilCacheTable. */    protected String name = null;    /** A hashtable containing a CacheLine object with a value and a loadTime for each element. */    public CacheLineTable cacheLineTable = null;    /** A count of the number of cache hits */    protected long hitCount = 0;    /** A count of the number of cache misses because it is not found in the cache */    protected long missCountNotFound = 0;    /** A count of the number of cache misses because it expired */    protected long missCountExpired = 0;    /** A count of the number of cache misses because it was cleared from the Soft Reference (ie garbage collection, etc) */    protected long missCountSoftRef = 0;    /** A count of the number of cache hits on removes */    protected long removeHitCount = 0;    /** A count of the number of cache misses on removes */    protected long removeMissCount = 0;        /** The maximum number of elements in the cache.     * If set to 0, there will be no limit on the number of elements in the cache.     */    protected int maxSize = 0;    protected int maxInMemory = 0;    /** Specifies the amount of time since initial loading before an element will be reported as expired.     * If set to 0, elements will never expire.     */    protected long expireTime = 0;    /** Specifies whether or not to use soft references for this cache, defaults to false */    protected boolean useSoftReference = false;    /** Specifies whether or not to use file base stored for this cache, defautls to false */    protected boolean useFileSystemStore = false;    private String fileStore = "data/utilcache";    /** The set of listeners to receive notifcations when items are modidfied(either delibrately or because they were expired). */    protected Set listeners = FastSet.newInstance();        /** Constructor which specifies the cacheName as well as the maxSize, expireTime and useSoftReference.     * The passed maxSize, expireTime and useSoftReference will be overridden by values from cache.properties if found.     * @param maxSize The maxSize member is set to this value     * @param expireTime The expireTime member is set to this value     * @param cacheName The name of the cache.     * @param useSoftReference Specifies whether or not to use soft references for this cache.     */    public UtilCache(String cacheName, int maxSize, int maxInMemory, long expireTime, boolean useSoftReference, boolean useFileSystemStore) {        this.maxSize = maxSize;        this.maxInMemory = maxInMemory;        this.expireTime = expireTime;        this.useSoftReference = useSoftReference;        this.useFileSystemStore = useFileSystemStore;        name = cacheName + this.getNextDefaultIndex(cacheName);        setPropertiesParams(cacheName);        utilCacheTable.put(name, this);    }    public UtilCache(String cacheName, int maxSize, long expireTime, boolean useSoftReference) {        this(cacheName, maxSize, maxSize, expireTime, useSoftReference, false);    }    /** Constructor which specifies the cacheName as well as the maxSize and expireTime.     * The passed maxSize and expireTime will be overridden by values from cache.properties if found.     * @param maxSize The maxSize member is set to this value     * @param expireTime The expireTime member is set to this value     * @param cacheName The name of the cache.     */    public UtilCache(String cacheName, int maxSize, long expireTime) {        this(cacheName, maxSize, expireTime, false);    }    /** Constructor which specifies the maxSize and expireTime.     * @param maxSize The maxSize member is set to this value     * @param expireTime The expireTime member is set to this value     */    public UtilCache(int maxSize, long expireTime) {        this.useSoftReference = false;        this.maxSize = maxSize;        this.expireTime = expireTime;        String name = "specified" + this.getNextDefaultIndex("specified");        setPropertiesParams(name);        utilCacheTable.put(name, this);    }    /** This constructor takes a name for the cache, puts itself in the utilCacheTable.     * It also uses the cacheName to lookup the initialization parameters from cache.properties.     * @param cacheName The name of the cache.     */    public UtilCache(String cacheName, boolean useSoftReference) {        name = cacheName + this.getNextDefaultIndex(cacheName);        this.useSoftReference = useSoftReference;        setPropertiesParams("default");        setPropertiesParams(cacheName);        utilCacheTable.put(name, this);    }    /** This constructor takes a name for the cache, puts itself in the utilCacheTable.     * It also uses the cacheName to lookup the initialization parameters from cache.properties.     * @param cacheName The name of the cache.     */    public UtilCache(String cacheName) {        name = cacheName + this.getNextDefaultIndex(cacheName);        setPropertiesParams("default");        setPropertiesParams(cacheName);        utilCacheTable.put(name, this);    }    /** Default constructor, all members stay at default values as defined in cache.properties, or the defaults in this file if cache.properties is not found, or there are no 'default' entries in it. */    public UtilCache() {        setPropertiesParams("default");        name = "default" + this.getNextDefaultIndex("default");        utilCacheTable.put(name, this);    }    protected String getNextDefaultIndex(String cacheName) {        Integer curInd = (Integer) UtilCache.defaultIndices.get(cacheName);        if (curInd == null) {            UtilCache.defaultIndices.put(cacheName, new Integer(1));            return "";        } else {            UtilCache.defaultIndices.put(cacheName, new Integer(curInd.intValue() + 1));            return Integer.toString(curInd.intValue() + 1);        }    }    public static String getPropertyParam(ResourceBundle res, String[] propNames, String parameter) {        String value = null;        for (int i = 0; i < propNames.length && value == null; i++ ) {            try {                value = res.getString(propNames[i] + '.' + parameter);            } catch (MissingResourceException e) {}        }        // don't need this, just return null        //if (value == null) {        //    throw new MissingResourceException("Can't find resource for bundle", res.getClass().getName(), Arrays.asList(propNames) + "." + parameter);        //}        return value;    }    protected void setPropertiesParams(String cacheName) {        setPropertiesParams(new String[] {cacheName});    }    public void setPropertiesParams(String[] propNames) {        ResourceBundle res = ResourceBundle.getBundle("cache");        if (res != null) {            try {                String value = getPropertyParam(res, propNames, "maxSize");                if (UtilValidate.isNotEmpty(value)) {                    Integer intValue = new Integer(value);                    if (intValue != null) {                        this.maxSize = intValue.intValue();                    }                }            } catch (Exception e) {                Debug.logWarning(e, "Error getting maxSize value from cache.properties file for propNames: " + propNames, module);            }            try {                String value = getPropertyParam(res, propNames, "maxInMemory");                if (UtilValidate.isNotEmpty(value)) {                    Integer intValue = new Integer(value);                    if (intValue != null) {                        this.maxInMemory = intValue.intValue();                    }                }            } catch (Exception e) {                Debug.logWarning(e, "Error getting maxInMemory value from cache.properties file for propNames: " + propNames, module);            }            try {                String value = getPropertyParam(res, propNames, "expireTime");                if (UtilValidate.isNotEmpty(value)) {                    Long longValue = new Long(value);                    if (longValue != null) {                        this.expireTime = longValue.longValue();                    }                }            } catch (Exception e) {                Debug.logWarning(e, "Error getting expireTime value from cache.properties file for propNames: " + propNames, module);            }            try {                String value = getPropertyParam(res, propNames, "useSoftReference");                if (value != null) {                    useSoftReference = "true".equals(value);                }            } catch (Exception e) {                Debug.logWarning(e, "Error getting useSoftReference value from cache.properties file for propNames: " + propNames, module);            }            try {                String value = getPropertyParam(res, propNames, "useFileSystemStore");                if (value != null) {                    useFileSystemStore = "true".equals(value);                }            } catch (Exception e) {                Debug.logWarning(e, "Error getting useFileSystemStore value from cache.properties file for propNames: " + propNames, module);            }            try {                String value = res.getString("cache.file.store");                if (value != null) {                    fileStore = value;                }            } catch (Exception e) {                Debug.logWarning(e, "Error getting cache.file.store value from cache.properties file for propNames: " + propNames, module);            }        }        int maxMemSize = this.maxInMemory;        if (maxMemSize == 0) maxMemSize = (int) maxSize;        this.cacheLineTable = new CacheLineTable(this.fileStore, this.name, this.useFileSystemStore, maxMemSize);    }    /** Puts or loads the passed element into the cache     * @param key The key for the element, used to reference it in the hastables and LRU linked list     * @param value The value of the element     */    public synchronized Object put(Object key, Object value) {        return put(key, value, expireTime);    }    /** Puts or loads the passed element into the cache     * @param key The key for the element, used to reference it in the hastables and LRU linked list     * @param value The value of the element     * @param expireTime how long to keep this key in the cache     */    public synchronized Object put(Object key, Object value, long expireTime) {        if (key == null) {            if (Debug.verboseOn()) Debug.logVerbose("In UtilCache tried to put with null key, using NullObject for cache " + this.getName(), module);            key = ObjectType.NULL;        }        CacheLine oldCacheLine;        if (expireTime > 0) {            oldCacheLine = (CacheLine) cacheLineTable.put(key, new CacheLine(value, useSoftReference, System.currentTimeMillis(), expireTime));        } else {            oldCacheLine = (CacheLine) cacheLineTable.put(key, new CacheLine(value, useSoftReference, expireTime));        }        if (oldCacheLine == null) {            noteAddition(key, value);            return null;        } else {            noteUpdate(key, value, oldCacheLine.getValue());            return oldCacheLine.getValue();        }    }    /** Gets an element from the cache according to the specified key.     * If the requested element hasExpired, it is removed before it is looked up which causes the function to return null.     * @param key The key for the element, used to reference it in the hastables and LRU linked list     * @return The value of the element specified by the key     */    public Object get(Object key) {        CacheLine line = getInternal(key, true);        if (line == null) {            return null;        } else {            return line.getValue();        }    }    protected CacheLine getInternalNoCheck(Object key) {        if (key == null) {            if (Debug.verboseOn()) Debug.logVerbose("In UtilCache tried to get with null key, using NullObject for cache " + this.getName(), module);            key = ObjectType.NULL;        }        CacheLine line = (CacheLine) cacheLineTable.get(key);        return line;    }        protected CacheLine getInternal(Object key, boolean countGet) {        CacheLine line = getInternalNoCheck(key);        if (line == null) {            if (countGet) missCountNotFound++;        } else if (line.softReferenceCleared()) {            removeInternal(key, false);            if (countGet) missCountSoftRef++;            line = null;        } else if (this.hasExpired(line)) {            // note that print.info in debug.properties cannot be checked through UtilProperties here, it would cause infinite recursion...            // if (Debug.infoOn()) Debug.logInfo("Element has expired with key " + key, module);            removeInternal(key, false);            if (countGet) missCountExpired++;            line = null;        } else {            if (countGet) hitCount++;        }

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -