cacheUtils

来源:互联网 发布:购买域名的网站 编辑:程序博客网 时间:2024/06/06 10:02

一个小小的内存缓存操作类,测试版,我自己都不敢用,


package test;import java.util.LinkedHashMap;import java.util.Map;import java.util.concurrent.ConcurrentHashMap;public class CacheUtils2 {    private static Map<String, Map<String, Object>> pool = new ConcurrentHashMap<String, Map<String, Object>>();    private static String name;    private static int maxNumber;    public CacheUtils2(String name, int maxNumber) {        super();        this.name = name;        this.maxNumber = maxNumber;    }    private static CacheUtils2 cache=null;      public static CacheUtils2 getInstance(String name,int maxNumber) {           if (cache == null) {                 cache = new CacheUtils2(name,maxNumber);           }            return cache;      }     public static void add(String key, String value) {        Map<String, Object> oldCache = pool.get(name);        if (oldCache == null) {            Map<String, Object> newCache = new LinkedHashMap<String, Object>();            newCache.put(key, value);            pool.put(name, newCache);        } else {            if (oldCache.size() >= maxNumber) {                oldCache.remove(oldCache.entrySet().iterator().next().getKey());                oldCache.put(key, value);            } else {                oldCache.put(key, value);            }        }    }    public static Object get(String key) {        Map<String, Object> Caches = pool.get(name);        return Caches.get(key);    }    public static void main(String[] args) {         CacheUtils2 u = CacheUtils2.getInstance("url", 25);        for (int i = 0; i <= 30; i++) {            u.add("key" + i, "value" + i);        }        u.add("key30", "value11100");        u.add("key29", "value11100");        u.add("key28", "value11100");        u.add("key27", "value11100");        for (int i = 0; i <= 30; i++) {            System.out.println(u.get("key" + i));        }        CacheUtils2 u2 = CacheUtils2.getInstance("url", 10);        for (int i = 0; i <= 30; i++) {            System.out.println(u.get("key" + i));        }    }}
原创粉丝点击