View Javadoc
1   package com.atlassian.cache.vcache;
2   
3   import java.io.Serializable;
4   import javax.annotation.Nonnull;
5   
6   import com.atlassian.cache.CacheException;
7   import com.atlassian.cache.CacheSettings;
8   import com.atlassian.cache.CachedReference;
9   import com.atlassian.cache.CachedReferenceListener;
10  import com.atlassian.cache.Supplier;
11  import com.atlassian.vcache.StableReadExternalCache;
12  import com.atlassian.vcache.VCacheUtils;
13  
14  import com.google.common.base.Throwables;
15  
16  import static java.util.Objects.requireNonNull;
17  
18  class ExternalCachedReference<V>
19          extends ManagedCacheSupport
20          implements CachedReference<V>
21  {
22      private static final String REFERENCE_KEY = "ReferenceKey";
23  
24      private final StableReadExternalCache<Serializable> delegate;
25      private final Supplier<V> supplier;
26  
27      ExternalCachedReference(String name,
28                              StableReadExternalCache<Serializable> delegate,
29                              Supplier<V> supplier,
30                              CacheSettings settings)
31      {
32          super(name, settings);
33          this.delegate = requireNonNull(delegate);
34          this.supplier = requireNonNull(supplier);
35      }
36  
37      @Nonnull
38      @Override
39      public V get()
40      {
41          try
42          {
43              //noinspection unchecked
44              return (V) VCacheUtils.join(delegate.get(REFERENCE_KEY, () -> Utils.asSerializable(supplier.get())));
45          }
46          catch (RuntimeException ex)
47          {
48              Throwables.propagateIfInstanceOf(Throwables.getRootCause(ex), CacheException.class);
49              throw new CacheException("Unknown failure", ex);
50          }
51      }
52  
53      @Override
54      public void reset()
55      {
56          delegate.remove(REFERENCE_KEY);
57      }
58  
59      @Override
60      public void addListener(@Nonnull CachedReferenceListener<V> listener, boolean includeValues)
61      {
62          throw new UnsupportedOperationException("Unsupported when using the VCache implementation");
63      }
64  
65      @Override
66      public void removeListener(@Nonnull CachedReferenceListener<V> listener)
67      {
68          throw new UnsupportedOperationException("Unsupported when using the VCache implementation");
69      }
70  
71      @Override
72      public void clear()
73      {
74          delegate.remove(REFERENCE_KEY);
75      }
76  
77      @Override
78      public boolean isLocal()
79      {
80          return false;
81      }
82  }