Although there are several third party cache available in Java such as enCache, soCache, Guava library - It's actually easy and important to know how to write a custom LRUCache (last recently used cache).
Simply put a cache is data loaded in to memory identified by a 'key'.
A ConcurrentLRUCache is essentially backed up by a ConcurrentHashMap and controlled by a ConcurrentLinkedQueue.
So let's see the sample code -
public class ConcurrentLRUCache<Key, Value> {
private final int maxSize;
private ConcurrentHashMap map<key, value>;
private ConcurrentLinkedQueue queue<key>,
public ConcurrentLRUCache(int maxSize) {
//Set the size of map
this.maxSize = maxSize;
map = new ConcurrentHashMap<key, value>(maxSize);
queue = new ConcurrentLinkedQueue();
}
public put(final Key key, final Value value) {
//If map already contains the key, you want to reinsert a new value for existing item, then remove the item from queue to maintain FIFO order (the key gets added to queue in the end of the method
if(map.containsKey(key) {
queue.remove(key);
}
//If the Size of queue is full, remove the first element added from map and queue
if(queue.size >= maxSize) {
//Retrieves the oldest element added and removes it from queue
key oldestKey = queue.poll;
if(oldestKey != null) {
//Remove oldest element added to the map
map.remove(oldestKey);
}
}
//Add value to map and queue
queue.put(key);
map.add(key, value);
}
public get(final Key key) {
return map.get(key);
}
}
}
Simply put a cache is data loaded in to memory identified by a 'key'.
A ConcurrentLRUCache is essentially backed up by a ConcurrentHashMap and controlled by a ConcurrentLinkedQueue.
So let's see the sample code -
public class ConcurrentLRUCache<Key, Value> {
private final int maxSize;
private ConcurrentHashMap map<key, value>;
private ConcurrentLinkedQueue queue<key>,
public ConcurrentLRUCache(int maxSize) {
//Set the size of map
this.maxSize = maxSize;
map = new ConcurrentHashMap<key, value>(maxSize);
queue = new ConcurrentLinkedQueue();
}
public put(final Key key, final Value value) {
//If map already contains the key, you want to reinsert a new value for existing item, then remove the item from queue to maintain FIFO order (the key gets added to queue in the end of the method
if(map.containsKey(key) {
queue.remove(key);
}
//If the Size of queue is full, remove the first element added from map and queue
if(queue.size >= maxSize) {
//Retrieves the oldest element added and removes it from queue
key oldestKey = queue.poll;
if(oldestKey != null) {
//Remove oldest element added to the map
map.remove(oldestKey);
}
}
//Add value to map and queue
queue.put(key);
map.add(key, value);
}
public get(final Key key) {
return map.get(key);
}
}
}
No comments:
Post a Comment