Created
May 17, 2012 07:26
-
-
Save kawasima/2717181 to your computer and use it in GitHub Desktop.
Bad cache
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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