Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package ru.ensemplix.storage;
- import java.util.LinkedHashMap;
- import java.util.Map;
- import java.util.Queue;
- import java.util.concurrent.ConcurrentLinkedQueue;
- import java.util.concurrent.Executors;
- import java.util.concurrent.TimeUnit;
- public class CachedStorage<V> extends LinkedHashMap<String, V> {
- private final Queue<V> add = new ConcurrentLinkedQueue<>();
- private final Queue<V> remove = new ConcurrentLinkedQueue<>();
- public CachedStorage(Storage<V> storage, String key) {
- super.putAll(storage.get(key));
- Executors.newSingleThreadScheduledExecutor().schedule(new Runnable() {
- @Override
- public void run() {
- try {
- System.out.println("Saving");
- while(!remove.isEmpty()) {
- storage.remove(remove.poll());
- }
- while(!add.isEmpty()) {
- storage.add(add.poll());
- }
- } catch(Exception e) {
- e.printStackTrace();
- }
- }
- }, 5, TimeUnit.SECONDS);
- }
- @Override
- public V put(String key, V value) {
- add.add(value);
- return super.put(key, value);
- }
- @Override
- public void putAll(Map<? extends String, ? extends V> map) {
- add.addAll(map.values());
- super.putAll(map);
- }
- @Override
- public V remove(Object key) {
- V value = super.remove(key);
- if(value != null) {
- remove.remove(value);
- }
- return value;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement