J2ME 技术的学习与实践者

[导入]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

posted on 2008-03-05 22:29 iwinyeah 阅读(58) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航: