View Javadoc

1   package com.atlassian.vcache;
2   
3   import java.time.Duration;
4   import java.util.Optional;
5   
6   /**
7    * Sample usage of a JvmCache.
8    */
9   public class JvmSample {
10      private final JvmCache<String, String> cache;
11  
12      public JvmSample(VCacheFactory factory) {
13          final JvmCacheSettings settings = new JvmCacheSettingsBuilder().
14                  maxEntries(10).
15                  defaultTtl(Duration.ofSeconds(42)).
16                  build();
17          cache = factory.getJvmCache("my.cache", settings);
18      }
19  
20      public String findFoo(String id) {
21          // Don't do this
22          final Optional<String> cachedValue = cache.get(id);
23          return cachedValue.orElseGet(() -> {
24              final String value = "id-" + id; // really? :-0
25              final Optional<String> afterPut = cache.putIfAbsent(id, value);
26  
27              return afterPut.orElse(value);
28          });
29      }
30  
31      public String findFoo2(String id) {
32          // do this
33          return cache.get(id, () -> "id-" + id);
34      }
35  
36      public int cacheSize() {
37          return cache.getKeys().size();
38      }
39  }