Forwarded from http://blog.riamaria.com/32/caching-in-java-with-lrumap/
So you want to cache recently used values? Well, there’s LRUMap for that!
LRU stands for Least Recently Used. LRUMap uses the LRU algorithm to delete the least recently used value in the map (presumably full) to make space for the newest entry.
You can use LRUMap through the Apache Commons Collections library. You can download the jar file here.
Beware: The LRUMap isn’t synchronized and thread safe. If you want to make it synchronized you can use java.util.Collections.synchronizedMap(Map) to wrap around the LRUMap and instantiate it like so…
So you want to cache recently used values? Well, there’s LRUMap for that!
LRU stands for Least Recently Used. LRUMap uses the LRU algorithm to delete the least recently used value in the map (presumably full) to make space for the newest entry.
You can use LRUMap through the Apache Commons Collections library. You can download the jar file here.
So, how do you instantiate this thing?
You can use the default constructor, or you can define its maximum size in the constructor. Its default maximum size is 100.Map<Object, Object> map = new LRUMap(); Map<Object, Object> map = new LRUMap( 100 ); |
Map<Object, Object> map = (Map<Object, Object>) Collections.synchronizedMap( new LRUMap()); Map<Object, Object> map = (Map<Object, Object>) Collections.synchronizedMap( new LRUMap( 100 )); |
Sample
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
| import java.util.Collections; import java.util.Map; import org.apache.commons.collections.map.LRUMap; public class LRUSample {
private static final int MAX_CAPACITY = 5 ;
public static void main(String[] args) {
Map<Integer, String> lruMap = (Map<Integer, String>) Collections.synchronizedMap( new LRUMap(MAX_CAPACITY));
for ( int i = 0 ; i < 30 ; i++) {
String string = "Entry " + (i + 1 );
lruMap.put(i, string);
System.out.println(lruMap.toString());
}
} } |
Comments
Post a Comment