title: ConcurrentHashMap removal of keys
body: <p>I'm trying to figure out how to write a thread-safe, expiring entries, cache. This cache will be used as a <code>no-hits</code> cache, so that if an entry is not found in some storage, I will put it in this cache and avoid the subsequent calls in the next minutes.</p>
  
  <p>There will be multiple threads reading and writing this cache.</p>
  
  <p>There will be just a single ThreadSafeCache instance in my application.</p>
  
  <p>I'm not sure if removing an entry in the contains method will arise synchronization issues.</p>
  
  <p>How may I test this class for thread-safety?</p>
  
  <p>Kind regards</p>
  
  <pre><code>public class ThreadSafeCache 
  {
      private final Clock clock = Clock.systemUTC();
      private final Duration expiration = Duration.ofMinutes(10);
      private final ConcurrentHashMap&lt;CacheKey, CacheValue&gt; internalMap = new ConcurrentHashMap&lt;&gt;();
  
      public boolean contains(String a, String b, byte[] c, String d)
      {
          CacheKey key = new CacheKey(a, b, c, d);
          CacheValue value = internalMap.get(key);
  
          if (value == null || value.isExpired())
          {
              internalMap.remove(key);
              return false;
          }
  
          return true;
      }
  
      public void put(String a, String b, byte[] c, String d)
      {
          internalMap.computeIfAbsent(new CacheKey(a, b, c, d), key -&gt; new CacheValue());
      }
  
  
      private class CacheValue
      {
          private final Instant insertionDate;
  
          private CacheValue()
          {
              this.insertionDate = clock.instant();
          }
  
          boolean isExpired()
          {
              return Duration.between(insertionDate, 
   clock.instant()).compareTo(expiration) &gt; 0;
          }
      }
  }
  </code></pre>