我知道实现起来很简单,但是我想重用已经存在的东西。
我要解决的问题是我为不同的页面,角色加载了配置(从XML,所以我想缓存它们),因此输入的组合可以增长很多(但99%的增长)。为了处理这个1%,我想在缓存中设置一些最大项目…
直到我在apache commons中找到了org.apache.commons.collections.map.LRUMap,它看起来还不错,但还想检查其他内容。有什么建议吗?
您可以使用LinkedHashMap(Java 1.4+):
// Create cache final int MAX_ENTRIES = 100; Map cache = new LinkedHashMap(MAX_ENTRIES+1, .75F, true) { // This method is called just after a new entry has been added public boolean removeEldestEntry(Map.Entry eldest) { return size() > MAX_ENTRIES; } }; // Add to cache Object key = "key"; cache.put(key, object); // Get object Object o = cache.get(key); if (o == null && !cache.containsKey(key)) { // Object not in cache. If null is not a possible value in the cache, // the call to cache.contains(key) is not needed } // If the cache is to be used by multiple threads, // the cache must be wrapped with code to synchronize the methods cache = (Map)Collections.synchronizedMap(cache);