CacheUtils 简单的内存操作工具类(根据条数缓存)

原创
2017/07/27 21:37
阅读数 16

自己写的不完整的cacheUtils工具类,做下笔记, 之所以叫cacheUtils2,因为cacheUtils不能用,

package test;

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

public class CacheUtils2 {
	
	//初始化一个XXX
	private static Map<String, Map<String, Object>> pool = new ConcurrentHashMap<String, Map<String, Object>>();
	private static String name;
	private static int maxNumber;
	
	public static CacheUtils2 instance(String name, int maxNumber) {
		CacheUtils2 cacheUtils = new CacheUtils2();
		cacheUtils.name = name;
		cacheUtils.maxNumber = maxNumber;
		return cacheUtils;
	}

	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.instance("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("key38", "value11100");
		u.add("key27", "value11100");
		for (int i = 0; i <= 35; i++) {
			System.out.println(u.get("key" + i));
		}
	}

}

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部