[導入]OpenBaseMovil 的高速對象緩存機制
網站: JavaEye 作者: iwinyeah 鏈接:http://iwinyeah.javaeye.com/blog/168482 發表時間: 2008年03月05日
聲明:本文系JavaEye網站發布的原創博客文章,未經作者書面許可,嚴禁任何網站轉載本文,否則必將追究法律責任!
一個簡單的高速對象緩存
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; // ...部分省略 // 構建函數,根據SIZE構建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而要使用另一個引用? final Hashtable cache = this.cache; if( !cache.containsKey( key ) ) { if( cache.size() == maxSize ) { discard(); // 如果Cache超過容量,按策略丟棄過時的對象 } // 在Cache中加入這個對象 cache.put( key, object ); // 相應也插入命中表第一位 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; } // ...部分省略 // 總是丟棄最后一個對象, private void discard() { final Object key = stamps.lastElement(); stamps.removeElement( key ); cache.remove( key ); } // 每次從Cache取用某key對象,都將它插到第一位 // 這樣不常用的對象將很快會被推至最后一位 private void touch( final Object key ) { stamps.removeElement( key ); stamps.insertElementAt( key, 0 ); } }
本文的討論也很精彩,瀏覽討論>>
JavaEye推薦
文章來源:http://iwinyeah.javaeye.com/blog/168482