InMemoryStore.java

  1. package net.morimekta.providence.storage;

  2. import net.morimekta.util.concurrent.ReadWriteMutex;
  3. import net.morimekta.util.concurrent.ReentrantReadWriteMutex;

  4. import javax.annotation.Nonnull;
  5. import java.util.Collection;
  6. import java.util.HashMap;
  7. import java.util.HashSet;
  8. import java.util.Map;

  9. /**
  10.  * Simple in-memory storage of providence messages. Uses a local hash map for
  11.  * storing the instances. The store is thread safe through using re-entrant
  12.  * read-write mutex handling, so reading can happen in parallel.
  13.  */
  14. public class InMemoryStore<K, M> implements ReadWriteStore<K,M> {
  15.     private final Map<K, M>      map;
  16.     private final ReadWriteMutex mutex;

  17.     public InMemoryStore() {
  18.         map   = new HashMap<>();
  19.         mutex = new ReentrantReadWriteMutex();
  20.     }

  21.     @Nonnull
  22.     @Override
  23.     public Map<K, M> getAll(@Nonnull Collection<K> keys) {
  24.         return mutex.lockForReading(() -> {
  25.             Map<K, M> out = new HashMap<>();
  26.             for (K key : keys) {
  27.                 if (map.containsKey(key)) {
  28.                     out.put(key, map.get(key));
  29.                 }
  30.             }
  31.             return out;
  32.         });
  33.     }

  34.     @Override
  35.     public boolean containsKey(@Nonnull K key) {
  36.         return mutex.lockForReading(() -> map.containsKey(key));
  37.     }

  38.     @Override @Nonnull
  39.     public Collection<K> keys() {
  40.         return mutex.lockForReading(() -> new HashSet<>(map.keySet()));
  41.     }

  42.     @Override
  43.     public int size() {
  44.         return mutex.lockForReading(map::size);
  45.     }

  46.     @Override
  47.     public void putAll(@Nonnull Map<K, M> values) {
  48.         mutex.lockForWriting(() -> map.putAll(values));
  49.     }

  50.     @Override
  51.     public void removeAll(Collection<K> keys) {
  52.         mutex.lockForWriting(() -> map.keySet().removeAll(keys));
  53.     }
  54. }