- 浏览: 199007 次
- 性别:
- 来自: 广州
文章分类
- 全部博客 (49)
- Hibernate 单向多对一 (1)
- hiberntae 单向一对多 (0)
- Hiberntae 双向一对多 (1)
- Hibernate 单向一对多 (1)
- Hibernate 外键一对一 (1)
- Hibernate 多对多 (1)
- Hibernate annotation (1)
- maven 配置Hibernate (1)
- java与maven的环境变量配置 (1)
- 我自己日常使用的工具类 (1)
- maven实战的pdf (1)
- maven 资料 (1)
- oracle的一些资料 (0)
- excel模板的src (0)
- vss 的学习 (0)
- sql 自己的一些语句 (0)
- 扎感1122 (0)
- 运行 vb6.0 vss 出现 um.dat may be corrupt 的解决方法 (0)
- maven ear template (0)
- java 设计模式 (1)
- java design (0)
- ejb3 学习 (0)
- 人生感想 (0)
- jpa的工程 (1)
- was 7.0 startup cmd (0)
- myeclipse download (0)
- java 遍历文件夹 (0)
- 比较俩个文件夹 (0)
- 并删除指定的文件 (0)
- jQuery基础教程下载地址 (0)
- eclipse plugin (0)
- jquery的学习 (0)
- pom 设置outputDirectory (1)
- maven-antrun-plugin (1)
- maven-resources-plugin (1)
- aspectj的学习 (0)
- Thread 并发的测试 (0)
- html (0)
- jfreechart 中文乱码 (1)
- jfreechart (0)
- java keytool (0)
- xhtml (0)
- maven buildnumber (0)
- xss (0)
- FilterValueHelper (0)
- 获取request的参数 (1)
- previous url (0)
- 动态update sql (1)
- xss danger word (0)
- noted (0)
- eclipse uml (0)
- xss list (0)
- xss check (0)
- js create ul li (0)
- css (0)
- java (0)
- xhtml example (0)
- menu (0)
- css 树 (0)
- hadoop (0)
- css tree (0)
- css 垂直导航栏 (0)
- css 垂直翻转的列表 (0)
- css 创建水平导航条 (0)
- css 菜单 (0)
- xml bean的使用 (0)
- dom4j xml (0)
- css menu但是不完善 (0)
- css 比较差的menu (0)
- 没完善的窗口关闭 (0)
- logout (0)
- swing source (0)
- css 简单 menu (0)
- swing 工程 (0)
- css 模板网 (0)
- css 菜单模板网 (0)
- 小菜单 (0)
- swing login demo (0)
- swing 菜单 (0)
- FileUtil (1)
- vss cmd line (0)
- ant (0)
- html table (0)
- java 获取ie language的值 (0)
- 艾古互动 (0)
- web (0)
- 我的艾古互动 (0)
- display tag (0)
- login html (0)
- javascript(获取或设置html元素的宽 (0)
- 高 (0)
- 坐标) (0)
- 项目5:画飘香.zip (0)
- 项目经验总结 (0)
- 第三章 (0)
- 溢出文本显示省略号的详细方法 (0)
- 刘德华 真我的风采 (0)
- 喜羊羊与灰太狼之给快乐加油 (0)
- css 虚线 (0)
- freemarker的例子 (1)
- js (0)
- javascript 创建右键菜单 (0)
- StringUtil (1)
- PatternUtil (0)
- 模拟FreeMarket的process (0)
- oracle 查看进程 (0)
- 二级菜单 (0)
- css 弹出窗口 (0)
- linux shell sftp (0)
- linux sheel (0)
- BeanRefUtil (0)
- GenericsUtils (0)
- linux command (0)
- a good source program (0)
- 一个策略模式的应用 (0)
- cache (1)
- html dl dt dd的试验 (0)
- sencha (0)
- java gzip 配置 (0)
- sencha 的Panel例子 (0)
- senca的form的例子 (0)
- 使用json的Seche Touch Form的例子 (0)
- sencha touch 的一个弹出窗口的例子 (0)
- 圆角div (0)
- Sencha Touch Panel 调用其它页面 (0)
- div 隐藏select overlay (0)
- jquery overlay use div button (0)
- sencha touch (0)
- Disable Right-click (0)
- multiple select option (0)
- jquery (0)
- 纯CSS实现圆角、可拖动的一个DIV弹出层 (0)
- 弹出div的内容 (0)
- pretty (0)
- 弹出圆角div的例子 (0)
- jstl (0)
- css 教程 url (0)
- oracle data function (0)
- clear bat (1)
- sencha touch overlay (0)
- 年会 (0)
- javascript动态添加tr节点 (0)
- 笔记本发出无线信号 (0)
- sencha touch bug (0)
- sencha touch overlay 测试 (0)
- music (0)
- Araxis Merge 下载 (0)
- oracle resource (1)
- js 闭包 (0)
- JS学习 (0)
- prettyPhoto bug (0)
- 制作图库 (0)
- oracle case 语句 (0)
- photo (0)
- poi (0)
- button link style in member site (0)
- js pop winodw (0)
- java 时区 (0)
- java 正则表达式的例子 (0)
- java mail (0)
- photos (0)
- as400 命令 (0)
- as400 CL example (0)
- html table 小技巧 (0)
- java dbcp 测试与配置 (0)
- frameset的使用 (0)
- java split (0)
- java 10%的概率 (0)
- java set 过滤 重复对象 (1)
- 浪潮之巅 (0)
- 交通规矩 (0)
- java web download file (0)
- java get websphere envoriment (0)
- java servlet download (0)
- show file (0)
- html 页面传值 (0)
- jmeter (0)
- html5 canvas rose (0)
- flash 爱的宣言 (0)
- Adobe Captivate 3 (0)
- jmeter 保持session的例子 (0)
- 旅游 (0)
- maven antrun plugin (0)
- maven Repository (0)
- oracle sqlj jdk problem (0)
- oracle sqlj error (0)
- oracle (0)
- maven 2.0.7 (0)
- oracle 版本 (0)
- java 验证Ip和域名 (0)
- FB lock (0)
- qq 密码 (0)
- div (0)
- 忘记心中情 (0)
- 忘尽心中情 (0)
- jsp 禁用缓存 (0)
- 3 points (0)
- java auth (0)
- C3 P0 datasource (0)
- dbcp datasource (0)
- paros-3.2.13 (0)
- java 转换 IE JESSIONID (0)
- 金曲情牽半世紀演唱會 (0)
- apache ecs (0)
- test html (0)
- IETester (0)
- xss attack (0)
- java 面试 (0)
- java反射工具类 (0)
- aaaaa (0)
- JavaScript 提升运行速度之循环篇 译文 (0)
- javascript Array 遍历优化 (0)
- javascript 代码优化 (0)
- js动态添加与删除ul中的li (0)
- jdbc preparedstatement inserrt into select (0)
- 电话号码 (0)
- 办理结婚手续 (0)
- 让DIV块在页面的某个位置固定 (0)
- endoing error (0)
- java filter space coding (0)
- javascript auto to move next tab (0)
- 各种颜色之RGB值 (0)
- javascript document.write (0)
- 激励 (0)
- java static 并发 (0)
- common js (0)
- was 的虚拟目录 (0)
- oracle dbcp config (0)
- check session timeout (0)
- Http学习之使用HttpURLConnection发送post和get请求 . (0)
- 一个chm (0)
- pdf电子书分享平台 (0)
- js print 去除页头页脚 (0)
- js print 去除url (0)
- head (0)
- 页头页脚 (0)
- js 打印去掉页头页脚 (0)
- xss input 应该过滤的word (0)
- Websphere applican server 的 JNDI的调用 (0)
- oracel 数据库连接数过大 (0)
- java 内部类 (0)
- javascript (0)
- java 发送短信 (0)
- js 验证 (0)
- 关闭弹出窗口 (0)
- DatabaseMetaData的应用 (0)
- table的使用 (0)
- tomcat 内存配置 (0)
- windows (0)
- xss 检查工具类 (0)
- oracle DataConvert (0)
- 一品威客 (0)
- mysql (0)
- ibatis in (0)
- js String 添加与删除一个元素 (0)
- sql 动态update (0)
- flexviewer (0)
- ie 离开页面提示 (0)
- flex 获取url (0)
- struts2 后台获取错误信息 (0)
- flex (0)
- oracle 树查询 (0)
- js 定时器 (0)
- sql server (0)
最新评论
-
songyubo:
AnnexXML ?
InputStream转换为File -
li370036149:
3q
maven实战的pdf
/**
* $RCSfile: Cache.java,v $
* $Revision: 1.5 $
* $Date: 2002/05/10 21:53:20 $
*
* Copyright (C) 1999-2002 CoolServlets, Inc. All rights reserved.
*
* This software is the proprietary information of CoolServlets, Inc.
* Use is subject to license terms.
*/
package com.jivesoftware.util;
/**
* cache的一般目的.它可以通过快速访问内存中标有唯一标记的对象集合!
* 所有的键和值添加到cache中必须实现 Serializable这个接口.
* 值可以实现Cacheable这个接口, 在cache里边可以更快的决定对象的大小.
* These restrictions allow a cache to never grow larger than a specified number
* of bytes and to optionally be distributed over a cluster of servers.<p>
*
* If the cache does grow too large, objects will be removed such that those
* that are accessed least frequently are removed first. Because expiration
* happens automatically, the cache makes <b>no</b> gaurantee as to how long
* an object will remain in cache after it is put in.<p>
*
* Optionally, a maximum lifetime for all objects can be specified. In that
* case, objects will be deleted from cache after that amount of time, even
* if they are frequently accessed. This feature is useful if objects put in
* cache represent data that should be periodically refreshed; for example,
* information from a database.<p>
*
* All cache operations are thread safe.<p>
*
* @see Cacheable
* @author Matt Tucker
*/
public interface Cache extends java.util.Map {
/**
* 返回这个cache的名字
*
* @return the name of the cache.
*/
String getName();
/**
* 返回cache的最大使用字节数.如果这个cache值大于最大值,我们就会把使用频率最少的记录删除
*
* @return the maximum size of the cache in bytes.
*/
int getMaxCacheSize();
/**
* 设置cache的最大值字节. If the cache grows
* larger than the max size, the least frequently used items will be removed.
*
* @param maxSize the maximum size of the cache in bytes.
*/
void setMaxCacheSize(int maxSize);
/**
* Returns the maximum number of milleseconds that any object can live
* in cache. Once the specified number of milleseconds passes, the object
* will be automatically expried from cache. If the max lifetime is set
* to -1, then objects never expire.
*
* @return the maximum number of milleseconds before objects are expired.
*/
long getMaxLifetime();
/**
* Sets the maximum number of milleseconds that any object can live
* in cache. Once the specified number of milleseconds passes, the object
* will be automatically expried from cache. If the max lifetime is set
* to -1, then objects never expire.
*
* @param maxLifetime the maximum number of milleseconds before objects are expired.
*/
void setMaxLifetime(long maxLifetime);
/**
* Returns the size of the cache contents in bytes. This value is only a
* rough approximation, so cache users should expect that actual VM
* memory used by the cache could be significantly higher than the value
* reported by this method.
*
* @return the size of the cache contents in bytes.
*/
int getCacheSize();
/**
* Returns the number of cache hits. A cache hit occurs every
* time the get method is called and the cache contains the requested
* object.<p>
*
* Keeping track of cache hits and misses lets one measure how efficient
* the cache is; the higher the percentage of hits, the more efficient.
*
* @return the number of cache hits.
*/
long getCacheHits();
/**
* Returns the number of cache misses. A cache miss occurs every
* time the get method is called and the cache does not contain the
* requested object.<p>
*
* Keeping track of cache hits and misses lets one measure how efficient
* the cache is; the higher the percentage of hits, the more efficient.
*
* @return the number of cache hits.
*/
long getCacheMisses();
}
**
* $RCSfile: DefaultCache.java,v $
* $Revision: 1.9 $
* $Date: 2002/07/15 13:19:01 $
*
* Copyright (C) 1999-2001 CoolServlets, Inc. All rights reserved.
*
* This software is the proprietary information of CoolServlets, Inc.
* Use is subject to license terms.
*/
package com.jivesoftware.util;
import java.util.*;
import java.io.*;
/**
* Default, non-distributed implementation of the Cache interface.
* The algorithm for cache is as follows: a HashMap is maintained for fast
* object lookup. Two linked lists are maintained: one keeps objects in the
* order they are accessed from cache, the other keeps objects in the order
* they were originally added to cache. When objects are added to cache, they
* are first wrapped by a CacheObject which maintains the following pieces
* of information:<ul>
* <li> The size of the object (in bytes).
* <li> A pointer to the node in the linked list that maintains accessed
* order for the object. Keeping a reference to the node lets us avoid
* linear scans of the linked list.
* <li> A pointer to the node in the linked list that maintains the age
* of the object in cache. Keeping a reference to the node lets us avoid
* linear scans of the linked list.</ul>
*
* To get an object from cache, a hash lookup is performed to get a reference
* to the CacheObject that wraps the real object we are looking for.
* The object is subsequently moved to the front of the accessed linked list
* and any necessary cache cleanups are performed. Cache deletion and expiration
* is performed as needed.
*
* @author Matt Tucker
*/
public class DefaultCache implements Cache {
/**
* The map the keys and values are stored in.
*/
protected Map map;
/**
* Linked list to maintain order that cache objects are accessed
* in, most used to least used.
*/
protected LinkedList lastAccessedList;
/**
* Linked list to maintain time that cache objects were initially added
* to the cache, most recently added to oldest added.
*/
protected LinkedList ageList;
/**
* Maximum size in bytes that the cache can grow to.
*/
private int maxCacheSize;
/**
* Maintains the current size of the cache in bytes.
*/
private int cacheSize = 0;
/**
* Maximum length of time objects can exist in cache before expiring.
*/
protected long maxLifetime;
/**
* Maintain the number of cache hits and misses. A cache hit occurs every
* time the get method is called and the cache contains the requested
* object. A cache miss represents the opposite occurence.<p>
*
* Keeping track of cache hits and misses lets one measure how efficient
* the cache is; the higher the percentage of hits, the more efficient.
*/
protected long cacheHits, cacheMisses = 0L;
/**
* The name of the cache.
*/
private String name;
/**
* Create a new cache and specify the maximum size of for the cache in
* bytes, and the maximum lifetime of objects.
*
* @param name a name for the cache.
* @param maxSize the maximum size of the cache in bytes.
* @param maxLifetime the maximum amount of time objects can exist in
* cache before being deleted. -1 means objects never expire.
*/
protected DefaultCache(String name, int maxSize, long maxLifetime) {
this.name = name;
this.maxCacheSize = maxSize;
this.maxLifetime = maxLifetime;
// Our primary data structure is a hash map. The default capacity of 11
// is too small in almost all cases, so we set it bigger.
map = new HashMap(103);
lastAccessedList = new LinkedList();
ageList = new LinkedList();
}
public synchronized Object put(Object key, Object value) {
// Delete an old entry if it exists.
remove(key);
int objectSize = calculateSize(value);
// If the object is bigger than the entire cache, simply don't add it.
if (objectSize > maxCacheSize * .90) {
System.err.println("Cache: " + name + " -- object with key " + key +
" is too large to fit in cache. Size is " + objectSize);
return value;
}
cacheSize += objectSize;
CacheObject cacheObject = new CacheObject(value, objectSize);
map.put(key, cacheObject);
// Make an entry into the cache order list.
LinkedListNode lastAccessedNode = lastAccessedList.addFirst(key);
// Store the cache order list entry so that we can get back to it
// during later lookups.
cacheObject.lastAccessedListNode = lastAccessedNode;
// Add the object to the age list
LinkedListNode ageNode = ageList.addFirst(key);
// We make an explicit call to currentTimeMillis() so that total accuracy
// of lifetime calculations is better than one second.
ageNode.timestamp = System.currentTimeMillis();
cacheObject.ageListNode = ageNode;
// If cache is too full, remove least used cache entries until it is
// not too full.
cullCache();
return value;
}
public synchronized Object get(Object key) {
// First, clear all entries that have been in cache longer than the
// maximum defined age.
deleteExpiredEntries();
CacheObject cacheObject = (CacheObject)map.get(key);
if (cacheObject == null) {
// The object didn't exist in cache, so increment cache misses.
cacheMisses++;
return null;
}
// The object exists in cache, so increment cache hits. Also, increment
// the object's read count.
cacheHits++;
cacheObject.readCount++;
// Remove the object from it's current place in the cache order list,
// and re-insert it at the front of the list.
cacheObject.lastAccessedListNode.remove();
lastAccessedList.addFirst(cacheObject.lastAccessedListNode);
return cacheObject.object;
}
public synchronized Object remove(Object key) {
CacheObject cacheObject = (CacheObject)map.get(key);
// If the object is not in cache, stop trying to remove it.
if (cacheObject == null) {
return null;
}
// remove from the hash map
map.remove(key);
// remove from the cache order list
cacheObject.lastAccessedListNode.remove();
cacheObject.ageListNode.remove();
// remove references to linked list nodes
cacheObject.ageListNode = null;
cacheObject.lastAccessedListNode = null;
// removed the object, so subtract its size from the total.
cacheSize -= cacheObject.size;
return cacheObject.object;
}
public synchronized void clear() {
Object [] keys = map.keySet().toArray();
for (int i=0; i<keys.length; i++) {
remove(keys[i]);
}
// Now, reset all containers.
map.clear();
lastAccessedList.clear();
lastAccessedList = new LinkedList();
ageList.clear();
ageList = new LinkedList();
cacheSize = 0;
cacheHits = 0;
cacheMisses = 0;
}
public int size() {
// First, clear all entries that have been in cache longer than the
// maximum defined age.
deleteExpiredEntries();
return map.size();
}
public boolean isEmpty() {
// First, clear all entries that have been in cache longer than the
// maximum defined age.
deleteExpiredEntries();
return map.isEmpty();
}
public Collection values() {
// First, clear all entries that have been in cache longer than the
// maximum defined age.
deleteExpiredEntries();
Object [] cacheObjects = map.values().toArray();
Object [] values = new Object[cacheObjects.length];
for (int i=0; i<cacheObjects.length; i++) {
values[i] = ((CacheObject)cacheObjects[i]).object;
}
return Collections.unmodifiableList(Arrays.asList(values));
}
public boolean containsKey(Object key) {
// First, clear all entries that have been in cache longer than the
// maximum defined age.
deleteExpiredEntries();
return map.containsKey(key);
}
public void putAll(Map map) {
for (Iterator i=map.keySet().iterator(); i.hasNext(); ) {
Object key = i.next();
Object value = map.get(key);
put(key, value);
}
}
public boolean containsValue(Object value) {
// First, clear all entries that have been in cache longer than the
// maximum defined age.
deleteExpiredEntries();
int objectSize = calculateSize(value);
CacheObject cacheObject = new CacheObject(value, objectSize);
return map.containsValue(cacheObject);
}
public Set entrySet() {
// First, clear all entries that have been in cache longer than the
// maximum defined age.
deleteExpiredEntries();
return Collections.unmodifiableSet(map.entrySet());
}
public String getName() {
return name;
}
public Set keySet() {
// First, clear all entries that have been in cache longer than the
// maximum defined age.
deleteExpiredEntries();
return Collections.unmodifiableSet(map.keySet());
}
public long getCacheHits() {
return cacheHits;
}
public long getCacheMisses() {
return cacheMisses;
}
public int getCacheSize() {
return cacheSize;
}
public int getMaxCacheSize() {
return maxCacheSize;
}
public void setMaxCacheSize(int maxCacheSize) {
this.maxCacheSize = maxCacheSize;
// It's possible that the new max size is smaller than our current cache
// size. If so, we need to delete infrequently used items.
cullCache();
}
public long getMaxLifetime() {
return maxLifetime;
}
public void setMaxLifetime(long maxLifetime) {
this.maxLifetime = maxLifetime;
}
/**
* Returns the size of an object in bytes. Determining size by serialization
* is only used as a last resort.
*
* @return the size of an object in bytes.
*/
private int calculateSize(Object object) {
// If the object is Cacheable, ask it its size.
if (object instanceof Cacheable) {
return ((Cacheable)object).getCachedSize();
}
// Coherence puts DataInputStream objects in cache.
else if (object instanceof java.io.DataInputStream) {
int size = 1;
try {
size = ((DataInputStream)object).available();
}
catch (IOException ioe) { }
return size;
}
// Check for other common types of objects put into cache.
else if (object instanceof Long) {
return CacheSizes.sizeOfLong();
}
else if (object instanceof Integer) {
return CacheSizes.sizeOfObject() + CacheSizes.sizeOfInt();
}
else if (object instanceof Boolean) {
return CacheSizes.sizeOfObject() + CacheSizes.sizeOfBoolean();
}
else if (object instanceof long []) {
long [] array = (long [])object;
return CacheSizes.sizeOfObject() + array.length * CacheSizes.sizeOfLong();
}
// Default behavior -- serialize the object to determine its size.
else {
int size = 1;
try {
// Default to serializing the object out to determine size.
NullOutputStream out = new NullOutputStream();
ObjectOutputStream outObj = new ObjectOutputStream(out);
outObj.writeObject(object);
size = out.size();
}
catch (IOException ioe) {
ioe.printStackTrace();
}
return size;
}
}
/**
* Clears all entries out of cache where the entries are older than the
* maximum defined age.
*/
protected synchronized void deleteExpiredEntries() {
// Check if expiration is turned on.
if (maxLifetime <= 0) {
return;
}
// Remove all old entries. To do this, we remove objects from the end
// of the linked list until they are no longer too old. We get to avoid
// any hash lookups or looking at any more objects than is strictly
// neccessary.
LinkedListNode node = ageList.getLast();
// If there are no entries in the age list, return.
if (node == null) {
return;
}
// Determine the expireTime, which is the moment in time that elements
// should expire from cache. Then, we can do an easy to check to see
// if the expire time is greater than the expire time.
long expireTime = CacheFactory.currentTime - maxLifetime;
while(expireTime > node.timestamp) {
// Remove the object
remove(node.object);
// Get the next node.
node = ageList.getLast();
// If there are no more entries in the age list, return.
if (node == null) {
return;
}
}
}
/**
* Removes objects from cache if the cache is too full. "Too full" is
* defined as within 3% of the maximum cache size. Whenever the cache is
* is too big, the least frequently used elements are deleted until the
* cache is at least 10% empty.
*/
protected final void cullCache() {
// See if the cache size is within 3% of being too big. If so, clean out
// cache until it's 10% free.
if (cacheSize >= maxCacheSize * .97) {
// First, delete any old entries to see how much memory that frees.
deleteExpiredEntries();
int desiredSize = (int)(maxCacheSize * .90);
while (cacheSize > desiredSize) {
// Get the key and invoke the remove method on it.
remove(lastAccessedList.getLast().object);
}
}
}
/**
* An extension of OutputStream that does nothing but calculate the number
* of bytes written through it.
*/
private static class NullOutputStream extends OutputStream {
int size = 0;
public void write(int b) throws IOException {
size++;
}
public void write(byte[] b) throws IOException {
size += b.length;
}
public void write(byte[] b, int off, int len) {
size += len;
}
/**
* Returns the number of bytes written out through the stream.
*
* @return the number of bytes written to the stream.
*/
public int size() {
return size;
}
}
}
* $RCSfile: Cache.java,v $
* $Revision: 1.5 $
* $Date: 2002/05/10 21:53:20 $
*
* Copyright (C) 1999-2002 CoolServlets, Inc. All rights reserved.
*
* This software is the proprietary information of CoolServlets, Inc.
* Use is subject to license terms.
*/
package com.jivesoftware.util;
/**
* cache的一般目的.它可以通过快速访问内存中标有唯一标记的对象集合!
* 所有的键和值添加到cache中必须实现 Serializable这个接口.
* 值可以实现Cacheable这个接口, 在cache里边可以更快的决定对象的大小.
* These restrictions allow a cache to never grow larger than a specified number
* of bytes and to optionally be distributed over a cluster of servers.<p>
*
* If the cache does grow too large, objects will be removed such that those
* that are accessed least frequently are removed first. Because expiration
* happens automatically, the cache makes <b>no</b> gaurantee as to how long
* an object will remain in cache after it is put in.<p>
*
* Optionally, a maximum lifetime for all objects can be specified. In that
* case, objects will be deleted from cache after that amount of time, even
* if they are frequently accessed. This feature is useful if objects put in
* cache represent data that should be periodically refreshed; for example,
* information from a database.<p>
*
* All cache operations are thread safe.<p>
*
* @see Cacheable
* @author Matt Tucker
*/
public interface Cache extends java.util.Map {
/**
* 返回这个cache的名字
*
* @return the name of the cache.
*/
String getName();
/**
* 返回cache的最大使用字节数.如果这个cache值大于最大值,我们就会把使用频率最少的记录删除
*
* @return the maximum size of the cache in bytes.
*/
int getMaxCacheSize();
/**
* 设置cache的最大值字节. If the cache grows
* larger than the max size, the least frequently used items will be removed.
*
* @param maxSize the maximum size of the cache in bytes.
*/
void setMaxCacheSize(int maxSize);
/**
* Returns the maximum number of milleseconds that any object can live
* in cache. Once the specified number of milleseconds passes, the object
* will be automatically expried from cache. If the max lifetime is set
* to -1, then objects never expire.
*
* @return the maximum number of milleseconds before objects are expired.
*/
long getMaxLifetime();
/**
* Sets the maximum number of milleseconds that any object can live
* in cache. Once the specified number of milleseconds passes, the object
* will be automatically expried from cache. If the max lifetime is set
* to -1, then objects never expire.
*
* @param maxLifetime the maximum number of milleseconds before objects are expired.
*/
void setMaxLifetime(long maxLifetime);
/**
* Returns the size of the cache contents in bytes. This value is only a
* rough approximation, so cache users should expect that actual VM
* memory used by the cache could be significantly higher than the value
* reported by this method.
*
* @return the size of the cache contents in bytes.
*/
int getCacheSize();
/**
* Returns the number of cache hits. A cache hit occurs every
* time the get method is called and the cache contains the requested
* object.<p>
*
* Keeping track of cache hits and misses lets one measure how efficient
* the cache is; the higher the percentage of hits, the more efficient.
*
* @return the number of cache hits.
*/
long getCacheHits();
/**
* Returns the number of cache misses. A cache miss occurs every
* time the get method is called and the cache does not contain the
* requested object.<p>
*
* Keeping track of cache hits and misses lets one measure how efficient
* the cache is; the higher the percentage of hits, the more efficient.
*
* @return the number of cache hits.
*/
long getCacheMisses();
}
**
* $RCSfile: DefaultCache.java,v $
* $Revision: 1.9 $
* $Date: 2002/07/15 13:19:01 $
*
* Copyright (C) 1999-2001 CoolServlets, Inc. All rights reserved.
*
* This software is the proprietary information of CoolServlets, Inc.
* Use is subject to license terms.
*/
package com.jivesoftware.util;
import java.util.*;
import java.io.*;
/**
* Default, non-distributed implementation of the Cache interface.
* The algorithm for cache is as follows: a HashMap is maintained for fast
* object lookup. Two linked lists are maintained: one keeps objects in the
* order they are accessed from cache, the other keeps objects in the order
* they were originally added to cache. When objects are added to cache, they
* are first wrapped by a CacheObject which maintains the following pieces
* of information:<ul>
* <li> The size of the object (in bytes).
* <li> A pointer to the node in the linked list that maintains accessed
* order for the object. Keeping a reference to the node lets us avoid
* linear scans of the linked list.
* <li> A pointer to the node in the linked list that maintains the age
* of the object in cache. Keeping a reference to the node lets us avoid
* linear scans of the linked list.</ul>
*
* To get an object from cache, a hash lookup is performed to get a reference
* to the CacheObject that wraps the real object we are looking for.
* The object is subsequently moved to the front of the accessed linked list
* and any necessary cache cleanups are performed. Cache deletion and expiration
* is performed as needed.
*
* @author Matt Tucker
*/
public class DefaultCache implements Cache {
/**
* The map the keys and values are stored in.
*/
protected Map map;
/**
* Linked list to maintain order that cache objects are accessed
* in, most used to least used.
*/
protected LinkedList lastAccessedList;
/**
* Linked list to maintain time that cache objects were initially added
* to the cache, most recently added to oldest added.
*/
protected LinkedList ageList;
/**
* Maximum size in bytes that the cache can grow to.
*/
private int maxCacheSize;
/**
* Maintains the current size of the cache in bytes.
*/
private int cacheSize = 0;
/**
* Maximum length of time objects can exist in cache before expiring.
*/
protected long maxLifetime;
/**
* Maintain the number of cache hits and misses. A cache hit occurs every
* time the get method is called and the cache contains the requested
* object. A cache miss represents the opposite occurence.<p>
*
* Keeping track of cache hits and misses lets one measure how efficient
* the cache is; the higher the percentage of hits, the more efficient.
*/
protected long cacheHits, cacheMisses = 0L;
/**
* The name of the cache.
*/
private String name;
/**
* Create a new cache and specify the maximum size of for the cache in
* bytes, and the maximum lifetime of objects.
*
* @param name a name for the cache.
* @param maxSize the maximum size of the cache in bytes.
* @param maxLifetime the maximum amount of time objects can exist in
* cache before being deleted. -1 means objects never expire.
*/
protected DefaultCache(String name, int maxSize, long maxLifetime) {
this.name = name;
this.maxCacheSize = maxSize;
this.maxLifetime = maxLifetime;
// Our primary data structure is a hash map. The default capacity of 11
// is too small in almost all cases, so we set it bigger.
map = new HashMap(103);
lastAccessedList = new LinkedList();
ageList = new LinkedList();
}
public synchronized Object put(Object key, Object value) {
// Delete an old entry if it exists.
remove(key);
int objectSize = calculateSize(value);
// If the object is bigger than the entire cache, simply don't add it.
if (objectSize > maxCacheSize * .90) {
System.err.println("Cache: " + name + " -- object with key " + key +
" is too large to fit in cache. Size is " + objectSize);
return value;
}
cacheSize += objectSize;
CacheObject cacheObject = new CacheObject(value, objectSize);
map.put(key, cacheObject);
// Make an entry into the cache order list.
LinkedListNode lastAccessedNode = lastAccessedList.addFirst(key);
// Store the cache order list entry so that we can get back to it
// during later lookups.
cacheObject.lastAccessedListNode = lastAccessedNode;
// Add the object to the age list
LinkedListNode ageNode = ageList.addFirst(key);
// We make an explicit call to currentTimeMillis() so that total accuracy
// of lifetime calculations is better than one second.
ageNode.timestamp = System.currentTimeMillis();
cacheObject.ageListNode = ageNode;
// If cache is too full, remove least used cache entries until it is
// not too full.
cullCache();
return value;
}
public synchronized Object get(Object key) {
// First, clear all entries that have been in cache longer than the
// maximum defined age.
deleteExpiredEntries();
CacheObject cacheObject = (CacheObject)map.get(key);
if (cacheObject == null) {
// The object didn't exist in cache, so increment cache misses.
cacheMisses++;
return null;
}
// The object exists in cache, so increment cache hits. Also, increment
// the object's read count.
cacheHits++;
cacheObject.readCount++;
// Remove the object from it's current place in the cache order list,
// and re-insert it at the front of the list.
cacheObject.lastAccessedListNode.remove();
lastAccessedList.addFirst(cacheObject.lastAccessedListNode);
return cacheObject.object;
}
public synchronized Object remove(Object key) {
CacheObject cacheObject = (CacheObject)map.get(key);
// If the object is not in cache, stop trying to remove it.
if (cacheObject == null) {
return null;
}
// remove from the hash map
map.remove(key);
// remove from the cache order list
cacheObject.lastAccessedListNode.remove();
cacheObject.ageListNode.remove();
// remove references to linked list nodes
cacheObject.ageListNode = null;
cacheObject.lastAccessedListNode = null;
// removed the object, so subtract its size from the total.
cacheSize -= cacheObject.size;
return cacheObject.object;
}
public synchronized void clear() {
Object [] keys = map.keySet().toArray();
for (int i=0; i<keys.length; i++) {
remove(keys[i]);
}
// Now, reset all containers.
map.clear();
lastAccessedList.clear();
lastAccessedList = new LinkedList();
ageList.clear();
ageList = new LinkedList();
cacheSize = 0;
cacheHits = 0;
cacheMisses = 0;
}
public int size() {
// First, clear all entries that have been in cache longer than the
// maximum defined age.
deleteExpiredEntries();
return map.size();
}
public boolean isEmpty() {
// First, clear all entries that have been in cache longer than the
// maximum defined age.
deleteExpiredEntries();
return map.isEmpty();
}
public Collection values() {
// First, clear all entries that have been in cache longer than the
// maximum defined age.
deleteExpiredEntries();
Object [] cacheObjects = map.values().toArray();
Object [] values = new Object[cacheObjects.length];
for (int i=0; i<cacheObjects.length; i++) {
values[i] = ((CacheObject)cacheObjects[i]).object;
}
return Collections.unmodifiableList(Arrays.asList(values));
}
public boolean containsKey(Object key) {
// First, clear all entries that have been in cache longer than the
// maximum defined age.
deleteExpiredEntries();
return map.containsKey(key);
}
public void putAll(Map map) {
for (Iterator i=map.keySet().iterator(); i.hasNext(); ) {
Object key = i.next();
Object value = map.get(key);
put(key, value);
}
}
public boolean containsValue(Object value) {
// First, clear all entries that have been in cache longer than the
// maximum defined age.
deleteExpiredEntries();
int objectSize = calculateSize(value);
CacheObject cacheObject = new CacheObject(value, objectSize);
return map.containsValue(cacheObject);
}
public Set entrySet() {
// First, clear all entries that have been in cache longer than the
// maximum defined age.
deleteExpiredEntries();
return Collections.unmodifiableSet(map.entrySet());
}
public String getName() {
return name;
}
public Set keySet() {
// First, clear all entries that have been in cache longer than the
// maximum defined age.
deleteExpiredEntries();
return Collections.unmodifiableSet(map.keySet());
}
public long getCacheHits() {
return cacheHits;
}
public long getCacheMisses() {
return cacheMisses;
}
public int getCacheSize() {
return cacheSize;
}
public int getMaxCacheSize() {
return maxCacheSize;
}
public void setMaxCacheSize(int maxCacheSize) {
this.maxCacheSize = maxCacheSize;
// It's possible that the new max size is smaller than our current cache
// size. If so, we need to delete infrequently used items.
cullCache();
}
public long getMaxLifetime() {
return maxLifetime;
}
public void setMaxLifetime(long maxLifetime) {
this.maxLifetime = maxLifetime;
}
/**
* Returns the size of an object in bytes. Determining size by serialization
* is only used as a last resort.
*
* @return the size of an object in bytes.
*/
private int calculateSize(Object object) {
// If the object is Cacheable, ask it its size.
if (object instanceof Cacheable) {
return ((Cacheable)object).getCachedSize();
}
// Coherence puts DataInputStream objects in cache.
else if (object instanceof java.io.DataInputStream) {
int size = 1;
try {
size = ((DataInputStream)object).available();
}
catch (IOException ioe) { }
return size;
}
// Check for other common types of objects put into cache.
else if (object instanceof Long) {
return CacheSizes.sizeOfLong();
}
else if (object instanceof Integer) {
return CacheSizes.sizeOfObject() + CacheSizes.sizeOfInt();
}
else if (object instanceof Boolean) {
return CacheSizes.sizeOfObject() + CacheSizes.sizeOfBoolean();
}
else if (object instanceof long []) {
long [] array = (long [])object;
return CacheSizes.sizeOfObject() + array.length * CacheSizes.sizeOfLong();
}
// Default behavior -- serialize the object to determine its size.
else {
int size = 1;
try {
// Default to serializing the object out to determine size.
NullOutputStream out = new NullOutputStream();
ObjectOutputStream outObj = new ObjectOutputStream(out);
outObj.writeObject(object);
size = out.size();
}
catch (IOException ioe) {
ioe.printStackTrace();
}
return size;
}
}
/**
* Clears all entries out of cache where the entries are older than the
* maximum defined age.
*/
protected synchronized void deleteExpiredEntries() {
// Check if expiration is turned on.
if (maxLifetime <= 0) {
return;
}
// Remove all old entries. To do this, we remove objects from the end
// of the linked list until they are no longer too old. We get to avoid
// any hash lookups or looking at any more objects than is strictly
// neccessary.
LinkedListNode node = ageList.getLast();
// If there are no entries in the age list, return.
if (node == null) {
return;
}
// Determine the expireTime, which is the moment in time that elements
// should expire from cache. Then, we can do an easy to check to see
// if the expire time is greater than the expire time.
long expireTime = CacheFactory.currentTime - maxLifetime;
while(expireTime > node.timestamp) {
// Remove the object
remove(node.object);
// Get the next node.
node = ageList.getLast();
// If there are no more entries in the age list, return.
if (node == null) {
return;
}
}
}
/**
* Removes objects from cache if the cache is too full. "Too full" is
* defined as within 3% of the maximum cache size. Whenever the cache is
* is too big, the least frequently used elements are deleted until the
* cache is at least 10% empty.
*/
protected final void cullCache() {
// See if the cache size is within 3% of being too big. If so, clean out
// cache until it's 10% free.
if (cacheSize >= maxCacheSize * .97) {
// First, delete any old entries to see how much memory that frees.
deleteExpiredEntries();
int desiredSize = (int)(maxCacheSize * .90);
while (cacheSize > desiredSize) {
// Get the key and invoke the remove method on it.
remove(lastAccessedList.getLast().object);
}
}
}
/**
* An extension of OutputStream that does nothing but calculate the number
* of bytes written through it.
*/
private static class NullOutputStream extends OutputStream {
int size = 0;
public void write(int b) throws IOException {
size++;
}
public void write(byte[] b) throws IOException {
size += b.length;
}
public void write(byte[] b, int off, int len) {
size += len;
}
/**
* Returns the number of bytes written out through the stream.
*
* @return the number of bytes written to the stream.
*/
public int size() {
return size;
}
}
}
相关推荐
### Cache性能分析实验知识点 #### 实验背景与目标 本实验旨在通过使用SimpleScalar模拟器对Cache性能进行深入分析,以此来加深对Cache基础知识、结构及其工作原理的理解。此外,还将探讨并量化Cache的主要参数...
JetCache是阿里巴巴开源的一款高性能、轻量级的分布式缓存框架,适用于微服务架构中的缓存场景。本文将详细介绍如何在SpringBoot项目中整合JetCache,并探讨其本地缓存和Redis缓存的使用,以及如何实现多缓存的并行...
Oracle数据库中的Buffer Cache和一般的Cache概念虽然相似,但它们在具体应用中有着不同的侧重点。首先,我们需要理解Buffer Cache的基本概念。在Oracle数据库系统中,Buffer Cache是内存结构的一部分,它存储了最近...
Java连接Cache数据库主要涉及到的是如何使用Java编程语言与Intersystems Cache数据库进行交互。Intersystems Cache是一款高性能、面向对象的数据库系统,广泛应用于医疗、金融等领域的复杂数据管理。在Java环境中,...
《PrimoCache重置工具详解及应用》 PrimoCache是一款高效、实用的硬盘缓存软件,它通过在系统内存中创建虚拟缓存,显著提升硬盘读写性能,从而优化系统运行速度。然而,如同大多数试用软件一样,PrimoCache在一定...
【Cache性能分析实验报告】 本实验旨在深入理解Cache的基本概念、结构和工作原理,通过实际操作分析Cache的容量、相联度和块大小对性能的影响,以及不同替换算法的效果。实验采用Vmware虚拟机上的Redhat 9.0 Linux...
该工程包含数据缓存D_Cache和指令缓存I_Cache的Verilog代码和仿真文件,Cache的详细技术参数包含在.v文件的注释中。 直接相连16KB D_Cache Cache写策略: 写回法+写分配 (二路)组相连16KB I_Cache Cache替换策略: ...
TI-6678 DSP多核编程中的Cache技术是一个复杂而重要的议题,尤其在多核处理环境下。Cache是计算机架构中用于减少处理器访问内存所需平均时间的一个高速数据存储区域。它作为处理器和主存储器之间的临时缓存,能够极...
### 分块矩阵优化Cache:深度解析与应用策略 #### 核心知识点概览: 1. **Cache基础原理**:理解高速缓存(Cache)在现代计算机系统中的关键作用及其内部结构,包括标记存储器和数据存储器的功能。 2. **Cache失效...
### Cache的工作原理详解 #### 一、引言 在现代计算机体系结构中,为了提高处理器访问数据的速度,引入了多种缓存技术。其中,Cache作为连接CPU与主存的重要环节,其工作原理对于理解计算机系统性能至关重要。本文...
在本“计算机体系结构cache实验报告”中,我们主要探讨了Cache存储过程的模拟和性能分析,重点关注了不同因素如关联方式、Cache容量、关联度和块大小对Cache性能的影响。实验采用控制变量法,通过操作系统试验中的...
《PrimoCache v3.09:硬盘缓存利器的深度解析》 PrimoCache,一个在IT领域中被广泛使用的高效硬盘缓存工具,其最新版本v3.09,为用户带来了更为优化的存储性能提升。这款软件的核心功能在于通过在内存中创建临时...
赠送jar包:cache-api-1.1.1.jar; 赠送原API文档:cache-api-1.1.1-javadoc.jar; 赠送源代码:cache-api-1.1.1-sources.jar; 赠送Maven依赖信息文件:cache-api-1.1.1.pom; 包含翻译后的API文档:cache-api-...
在计算机系统中,Cache是一种高速数据存储部件,用于暂时存储CPU频繁访问的内存数据,以减少主内存与CPU之间的数据传输延迟,提高系统的整体性能。本文将深入探讨基于AXI4(Advanced eXtensible Interface)总线协议...
全相联Cache( Fully-Associative Cache)是Cache组织方式的一种,与直接映射Cache和组相联Cache不同,它的每一个块都可以映射到Cache的任何一个位置上,这提供了更大的灵活性,但也带来了更高的复杂性。 全相联...
标题"jdbc连接cache的demo及jar包,自己备份.rar"指出这是一个关于使用JDBC(Java Database Connectivity)连接Cache数据库的示例项目,其中包含了必要的jar包,并且用户已经将其作为个人备份保存。这里的“Cache”...
Guava Cache是Google Guava库中的一个强大特性,它提供了高效的本地缓存解决方案,用于存储经常访问的数据,以减少对远程服务或计算的调用,从而提高应用性能。本案例代码将详细介绍Guava Cache的使用,包括缓存的...
《Nginx Cache Purge:高效管理Web缓存的利器》 在当今互联网环境中,Web服务器的性能优化至关重要,而缓存技术则是其中的关键一环。Nginx,以其高性能、稳定性以及模块化的特性,成为了许多网站首选的反向代理和...
然而,DMA和Cache之间存在一致性问题,特别是在某些嵌入式平台上,DMA操作可能会绕过Cache,导致数据不一致,这就需要通过一系列策略来确保Cache一致性。 在DMA机制中,有两类主要的Cache一致性问题:流式DMA...
计算机组成原理实验指导书中的“实验3 直接相联Cache设计”着重讲解了Cache的基础知识,特别是直接相联Cache的结构、设计方法以及其实现。以下是对实验内容的详细阐述: 1. **直接相联Cache的基本结构**: - **...