Last active
August 1, 2016 16:42
-
-
Save xnull/e08d8a6e1208a60b868d40ff5a128f40 to your computer and use it in GitHub Desktop.
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
public static class Cacher { | |
private static final ConcurrentSkipListMap<CacherKey, Integer> cache = new ConcurrentSkipListMap<CacherKey, Integer>(); | |
public void put(String key, Integer value) { | |
if (cache.size() >= 10) { | |
cache.pollLastEntry(); | |
} | |
cache.put(new CacherKey(System.currentTimeMillis(), key), value); | |
} | |
public static class CacherKey implements Comparable<CacherKey> { | |
public final Long ts; | |
public final String key; | |
public CacherKey(Long ts, String key) { | |
this.ts = ts; | |
this.key = key; | |
} | |
@Override | |
public boolean equals(Object o) { | |
if (this == o) return true; | |
if (o == null || getClass() != o.getClass()) return false; | |
CacherKey cacherKey = (CacherKey) o; | |
return key != null ? key.equals(cacherKey.key) : cacherKey.key == null; | |
} | |
@Override | |
public int hashCode() { | |
return key != null ? key.hashCode() : 0; | |
} | |
@Override | |
public int compareTo(CacherKey other) { | |
if (other.key.equals(key)){ | |
return 0; | |
} | |
if (other.ts < ts) { | |
return -1; | |
} else if (other.ts > ts) { | |
return 1; | |
} else { | |
return 0; | |
} | |
} | |
@Override | |
public String toString() { | |
return "CacherKey{" + | |
"ts=" + ts + | |
", key='" + key + '\'' + | |
'}'; | |
} | |
} | |
public ConcurrentSkipListMap<CacherKey, Integer> getCache() { | |
return cache; | |
} | |
public static void main(String[] args) throws InterruptedException { | |
ConcurrentSkipListMap<String, Integer> vv = new ConcurrentSkipListMap<String, Integer>(); | |
vv.put("1", 1); | |
vv.put("1", 1); | |
vv.put("1", 1); | |
System.out.println(vv.size()); | |
Cacher c = new Cacher(); | |
c.put("1", 1); | |
pause(); | |
c.put("2", 2); | |
pause(); | |
c.put("3", 3); | |
for (Integer i = 1; i < 4; i++) { | |
pause(); | |
c.put(i.toString(), i); | |
} | |
for (Map.Entry<CacherKey, Integer> entry : c.getCache().entrySet()) { | |
System.out.println("Key: " + entry.getKey() + ", value: " + entry.getValue()); | |
} | |
} | |
private static void pause() throws InterruptedException { | |
Thread.currentThread().sleep(3); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Key: CacherKey{ts=1470069695879, key='3'}, value: 3
Key: CacherKey{ts=1470069695876, key='2'}, value: 2
Key: CacherKey{ts=1470069695872, key='1'}, value: 1
Key: CacherKey{ts=1470069695864, key='3'}, value: 3
Key: CacherKey{ts=1470069695860, key='2'}, value: 2
Key: CacherKey{ts=1470069695857, key='1'}, value: 1