Skip to content

Instantly share code, notes, and snippets.

@kawasima
Created May 17, 2012 07:26
Show Gist options
  • Save kawasima/2717181 to your computer and use it in GitHub Desktop.
Save kawasima/2717181 to your computer and use it in GitHub Desktop.
Bad cache
import java.util.ArrayList;
import java.util.UUID;
import java.util.WeakHashMap;
import org.junit.Test;
public class BadCache {
@Test
public void test() {
final WeakHashMap<String, CacheObject> cache = new WeakHashMap<String, CacheObject>();
final ArrayList<String> keyList = new ArrayList<String>();
new Thread(new Runnable() {
public void run() {
for(;;) {
int i=0;
synchronized (cache) {
long from = System.currentTimeMillis();
for(String key: cache.keySet()) {
CacheObject obj = cache.get(key);
if (obj.expires < from) {
i++;
keyList.remove(key);
}
}
System.out.println("Removed Cache="+ i + ", " + (System.currentTimeMillis() - from) + "ms");
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
for (;;) {
String key = UUID.randomUUID().toString();
synchronized(cache) {
CacheObject obj = new CacheObject();
obj.expires = Math.round(Math.random() * 10000);
obj.obj = UUID.randomUUID().toString();
cache.put(key, obj);
if (keyList.size() < 10000)
keyList.add(key);
}
}
}
static class CacheObject {
public long expires;
public String obj;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment