網(wǎng)站:
JavaEye
作者:
iwinyeah
鏈接:
http://iwinyeah.javaeye.com/blog/168482
發(fā)表時(shí)間: 2008年03月05日
聲明:本文系JavaEye網(wǎng)站發(fā)布的原創(chuàng)博客文章,未經(jīng)作者書面許可,嚴(yán)禁任何網(wǎng)站轉(zhuǎn)載本文,否則必將追究法律責(zé)任!
一個(gè)簡(jiǎn)單的高速對(duì)象緩存
public class SimpleCache
{
private static long wideHits;
private static long wideMisses;
private Hashtable cache;
private Vector stamps;
private int maxSize;
private long hits;
private long misses;
// ...部分省略
// 構(gòu)建函數(shù),根據(jù)SIZE構(gòu)建Cache和命中表
public SimpleCache( final int size )
{
this.maxSize = size;
cache = new Hashtable( size );
stamps = new Vector( size );
}
// ...部分省略
public void add( final Object key, final Object object )
{
// 為什么不直接使用cache而要使用另一個(gè)引用?
final Hashtable cache = this.cache;
if( !cache.containsKey( key ) )
{
if( cache.size() == maxSize )
{
discard(); // 如果Cache超過(guò)容量,按策略丟棄過(guò)時(shí)的對(duì)象
}
// 在Cache中加入這個(gè)對(duì)象
cache.put( key, object );
// 相應(yīng)也插入命中表第一位
stamps.insertElementAt( key, 0 );
}
else
{
// 更新Cache
cache.put( key, object );
// 也算命中一次
touch( key );
}
}
// ...部分省略
public synchronized Object get( final Object key )
{
final Object o = cache.get( key );
if( o != null )
{
hits++;
wideHits++;
// 算命中一次
touch( key );
}
else
{
misses++;
wideMisses++;
}
return o;
}
// ...部分省略
// 總是丟棄最后一個(gè)對(duì)象,
private void discard()
{
final Object key = stamps.lastElement();
stamps.removeElement( key );
cache.remove( key );
}
// 每次從Cache取用某key對(duì)象,都將它插到第一位
// 這樣不常用的對(duì)象將很快會(huì)被推至最后一位
private void touch( final Object key )
{
stamps.removeElement( key );
stamps.insertElementAt( key, 0 );
}
}
本文的討論也很精彩,瀏覽討論>>
JavaEye推薦
文章來(lái)源:
http://iwinyeah.javaeye.com/blog/168482