Advertisement
Guest User

Untitled

a guest
Feb 8th, 2016
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.62 KB | None | 0 0
  1. package ru.ensemplix.storage;
  2.  
  3. import java.util.LinkedHashMap;
  4. import java.util.Map;
  5. import java.util.Queue;
  6. import java.util.concurrent.ConcurrentLinkedQueue;
  7. import java.util.concurrent.Executors;
  8. import java.util.concurrent.TimeUnit;
  9.  
  10.  
  11. public class CachedStorage<V> extends LinkedHashMap<String, V> {
  12.  
  13. private final Queue<V> add = new ConcurrentLinkedQueue<>();
  14. private final Queue<V> remove = new ConcurrentLinkedQueue<>();
  15.  
  16. public CachedStorage(Storage<V> storage, String key) {
  17. super.putAll(storage.get(key));
  18.  
  19. Executors.newSingleThreadScheduledExecutor().schedule(new Runnable() {
  20. @Override
  21. public void run() {
  22. try {
  23. System.out.println("Saving");
  24.  
  25. while(!remove.isEmpty()) {
  26. storage.remove(remove.poll());
  27. }
  28.  
  29. while(!add.isEmpty()) {
  30. storage.add(add.poll());
  31. }
  32. } catch(Exception e) {
  33. e.printStackTrace();
  34. }
  35. }
  36. }, 5, TimeUnit.SECONDS);
  37. }
  38.  
  39. @Override
  40. public V put(String key, V value) {
  41. add.add(value);
  42. return super.put(key, value);
  43. }
  44.  
  45. @Override
  46. public void putAll(Map<? extends String, ? extends V> map) {
  47. add.addAll(map.values());
  48. super.putAll(map);
  49. }
  50.  
  51. @Override
  52. public V remove(Object key) {
  53. V value = super.remove(key);
  54.  
  55. if(value != null) {
  56. remove.remove(value);
  57. }
  58.  
  59. return value;
  60. }
  61.  
  62.  
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement