title: How to create a write-behind cache from inmemory to database?
body: <p>My goal is to cache data inmemory for 60s. As soon as the entry is read again from cache, I want to remove it from cache (permit single reads only).</p>
  
  <p>If those 60s expired in the meantime and the entry is still available in cache, I want to writebehind the entry into a database.</p>
  
  <p>Is there any existing technology/spring/apache framework that already offers such a cache?
  (sidenote: I don't want to use complex libraries like redis, ehcache etc for such a simple usecase).</p>
  
  <p>If set up manually, I'd be doing as follows. But probably there are better options?</p>
  
  <pre><code>@Service
  public class WriteBehindCache {
      static class ObjectEntry {
          Object data;
          LocalDateTime timestamp;
  
          public ObjectEntry(Object data) {
                this.data = data;
                timestamp = LocalDateTime.now();
          }
      }
  
      Map&lt;String, ObjectEntry&gt; cache = new ConcurrentHashMap&lt;&gt;();
  
      //batch every minute
      @Scheduled(fixedRate = 60000)
      public void writeBehind() {
          LocalDateTime now = LocalDateTime.now();
          List&lt;ObjectEntry&gt; outdated = cache.values()
               .filter(entry -&gt; entry.getValue().timestamp.plusSeconds(60).isBefore(now))
               .collect(Collectors.toList());
  
          databaseService.persist(outdated);
          cache.removeAll(outdated); //pseudocode
      }
  
      //always keep most recent entry
      public void add(String key, Object data) {
          cache.put(key, new ObjectEntry(data));
      }
  
      //fallback lookup to database if cache is empty
      public Object get(String key) {
          ObjectEntry entry = cache.remove(key);
          if (entry == null) {
              entry = databaseService.query(key);
              if (entry != null)  databaseService.remove(entry);
          }
          return entry;
      }
  }
  </code></pre>