Skip to content

Instantly share code, notes, and snippets.

@pandey-adarsh147
Created January 12, 2015 20:32
Show Gist options
  • Save pandey-adarsh147/cfce8bcf12b12e35845f to your computer and use it in GitHub Desktop.
Save pandey-adarsh147/cfce8bcf12b12e35845f to your computer and use it in GitHub Desktop.
LRUCache main class
package com.vectordirection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
/**
* Created by adarshpandey on 1/12/15.
*/
public class LRUCache<Key, Item extends CacheableItem<Key>> implements Runnable {
private final int maxSize;
private final Integer mutex = 1;
private Semaphore semaphore = new Semaphore(0);
private final Map<Key, Item> cache;
private boolean isKeepRunning = true;
public LRUCache(int cacheSize) {
cache = new HashMap<>();
maxSize = cacheSize;
isKeepRunning = true;
Thread thread = new Thread(this);
thread.start();
}
public int size() {
return cache.size();
}
public Item getValue(Key key) {
return cache.get(key);
}
public void add(Item item) {
synchronized (mutex) {
if (cache.containsKey(item.getKey())) {
cache.remove(item.getKey());
}
cache.put(item.getKey(), item);
semaphore.release();
}
}
public void shutdown() {
synchronized (mutex) {
isKeepRunning = false;
semaphore.release();
}
}
public void prune() {
synchronized (mutex) {
Iterator<Map.Entry<Key, Item>> itemIterator = cache.entrySet().iterator();
while (itemIterator.hasNext()) {
itemIterator.next();
if (cache.size() > maxSize) {
itemIterator.remove();
} else {
break;
}
}
}
}
@Override
public void run() {
while (isKeepRunning) {
try {
semaphore.tryAcquire(5000, TimeUnit.MILLISECONDS);
semaphore.drainPermits();
if (isKeepRunning) {
prune();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment