cacheUtils

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


package test;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class CacheUtils2 {

    private static Map> pool = new ConcurrentHashMap>();
    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 oldCache = pool.get(name);
        if (oldCache == null) {
            Map newCache = new LinkedHashMap();
            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 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));
        }
    }

}

你可能感兴趣的:(笔记)