Java爱好者

一个坚定的Java爱好者,欢迎和我讨论
随笔 - 7, 文章 - 8, 评论 - 6, 引用 - 0
数据加载中……

一个简单的Cache工具类,支持多线程


import java.util.Calendar;
import java.util.HashMap;
import java.util.Hashtable;

public class CacheHelper {
    public final static int default_interval_second = 20;
    public static boolean   ISDEBUG                 = true;
    private static HashMap  map                     = new HashMap();
    private static Object   obj                     = new Object();

    public static ICache getCache(String uniquekey) {
        synchronized (obj) {
            ICache ic = (ICache) map.get(uniquekey);
            if (ic == null) {
                ic = new CacheEntity(uniquekey);
                map.put(uniquekey, ic);
            }
            return ic;
        }
    }

    public interface ICache {
        Object get();

        Object get(long timestamp);

        void set(Object obj);

        void set(long timestamp, Object obj);

        void clear(String regx);

        void clearAll();
    }

    private static class CacheEntity implements ICache {
        private Hashtable hm        = new Hashtable();
        private Object    uniquekey = this;
        private long      timestamp = Long.MIN_VALUE;

        public CacheEntity(Object uniquekey) {
            this.uniquekey = uniquekey;
        }

        public Object get(long timestamp) {
            if (timestamp <= this.timestamp) {
                // 当前时间在设定的过期时间之前,表示还没有过期。
                // 如果还没过期,那么就返回。
                Object obj = hm.get(uniquekey);
                if (ISDEBUG && obj != null) {
                    // 输出日志。
                    System.out.println("[" + timestamp + "][Reading cache][" + uniquekey + "]...");
                }
                return obj;
            }
            else {
                // 清理垃圾。
                hm.remove(uniquekey);
                return null;
            }
        }

        public void set(long timestamp, Object obj) {
            this.timestamp = timestamp;
            hm.put(uniquekey, obj);
        }

        public Object get() {
            Calendar cal = Calendar.getInstance();
            return get(cal.getTimeInMillis());
        }

        public void set(Object obj) {
            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.SECOND, default_interval_second);
            set(cal.getTimeInMillis(), obj);
        }

        public void clear(String regx) {
            java.util.Enumeration keys = hm.keys();
            while (keys.hasMoreElements()) {
                String key = (String) keys.nextElement();
                if (key.matches(regx)) {
                    hm.remove(key);
                }
            }
        }

        public void clearAll() {
            hm.clear();
        }
    }
}

posted on 2006-08-03 09:29 JStar 阅读(1251) 评论(1)  编辑  收藏

评论

# re: 一个简单的Cache工具类,支持多线程[未登录]  回复  更多评论   

我觉得写的一般
有很多问题存在
2009-10-09 15:56 | 新手

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


网站导航: