fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. LRUCacheLHM<Integer, String> cache = new LRUCacheLHM<>(5);
  13. System.out.println("In:quick"+" Out:"+cache.place(0, "quick"));
  14. System.out.println("In:brown"+" Out:"+cache.place(1, "brown"));
  15. System.out.println("In:fox"+" Out:"+cache.place(2, "fox"));
  16. System.out.println("In:jumps"+" Out:"+cache.place(3, "jumps"));
  17. System.out.println("In:over"+" Out:"+cache.place(4, "over"));
  18. System.out.println("In:the"+" Out:"+cache.place(5, "the"));
  19. System.out.println("In:lazy"+" Out:"+cache.place(6, "lazy"));
  20. System.out.println("In:dog"+" Out:"+cache.place(7, "dog"));
  21. }
  22. }
  23.  
  24. class LRUCacheLHM<K,V> extends LinkedHashMap<K,V> {
  25.  
  26. private int capacity;
  27.  
  28. public LRUCacheLHM(int capacity) {
  29. //1 extra element as add happens before remove (101), and load factor big
  30. //enough to avoid triggering resize. True = keep in access order.
  31. super(capacity + 1, 1.1f, true);
  32. this.capacity = capacity;
  33. }
  34. private ThreadLocal<Map.Entry<K,V>> removed = new ThreadLocal<Map.Entry<K,V>>();
  35. private ThreadLocal<Boolean> report = new ThreadLocal<Boolean>();
  36. {
  37. report.set(false);
  38. }
  39. @Override
  40. public boolean removeEldestEntry(Map.Entry<K,V> eldest) {
  41. boolean res = size() > capacity;
  42. if (res && report.get()) {
  43. removed.set(eldest);
  44. }
  45. return res;
  46. }
  47. public Map.Entry<K,V> place(K k, V v) {
  48. report.set(true);
  49. put(k, v);
  50. try {
  51. return removed.get();
  52. } finally {
  53. removed.set(null);
  54. report.set(false);
  55. }
  56. }
  57.  
  58. }
Success #stdin #stdout 0.1s 320320KB
stdin
Standard input is empty
stdout
In:quick Out:null
In:brown Out:null
In:fox Out:null
In:jumps Out:null
In:over Out:null
In:the Out:0=quick
In:lazy Out:1=brown
In:dog Out:2=fox