Skip to content

Instantly share code, notes, and snippets.

@cscotta
Created September 2, 2011 02:57
Show Gist options
  • Select an option

  • Save cscotta/1187836 to your computer and use it in GitHub Desktop.

Select an option

Save cscotta/1187836 to your computer and use it in GitHub Desktop.
// Run with:
java -cp . -XX:+UseConcMarkSweepGC -XX:+UseParNewGC -XX:ParallelCMSThreads=24 -XX:+PrintGCDetails -XX:+PrintGCDateStamps Repro
import java.util.Map;
import java.util.Random;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
class Repro {
public static void main(String[] args) {
LRUCache<String, String> cache = new LRUCache<String, String>(10000000);
Random random = new Random();
while (true) {
cache.put("This is a string." + random.nextInt(), "This is a string." + random.nextInt());
}
}
// This naive LRUCache aped from http://www.source-code.biz/snippets/java/6.htm
public static class LRUCache<K,V> {
private static final float hashTableLoadFactor = 0.75f;
private LinkedHashMap<K,V> map;
private int cacheSize;
public LRUCache (int cacheSize) {
this.cacheSize = cacheSize;
int hashTableCapacity = (int)Math.ceil(cacheSize / hashTableLoadFactor) + 1;
map = new LinkedHashMap<K,V>(hashTableCapacity, hashTableLoadFactor, true) {
private static final long serialVersionUID = 1;
@Override protected boolean removeEldestEntry (Map.Entry<K,V> eldest) {
return size() > LRUCache.this.cacheSize;
}
};
}
public synchronized V get (K key) { return map.get(key); }
public synchronized void put (K key, V value) { map.put (key, value); }
public synchronized void clear() { map.clear(); }
public synchronized int usedEntries() { return map.size(); }
public synchronized Collection<Map.Entry<K,V>> getAll() { return new ArrayList<Map.Entry<K,V>>(map.entrySet()); }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment