1 package com.atlassian.cache.vcache;
2
3 import java.util.Collection;
4 import javax.annotation.Nonnull;
5 import javax.annotation.Nullable;
6
7 import com.atlassian.cache.Cache;
8 import com.atlassian.cache.CacheEntryListener;
9 import com.atlassian.cache.CacheLoader;
10 import com.atlassian.cache.CacheSettings;
11 import com.atlassian.cache.Supplier;
12 import com.atlassian.vcache.JvmCache;
13
14 import static java.util.Objects.requireNonNull;
15
16 class JvmCacheDelegate<K, V>
17 extends ManagedCacheSupport
18 implements Cache<K, V>
19 {
20 private final JvmCache<K, V> delegate;
21 private final CacheLoader<K, V> cacheLoader;
22
23 public JvmCacheDelegate(String name,
24 JvmCache<K, V> delegate,
25 @Nullable CacheLoader<K, V> cacheLoader,
26 CacheSettings settings)
27 {
28 super(name, settings);
29 this.delegate = requireNonNull(delegate);
30 this.cacheLoader = cacheLoader;
31 }
32
33 @Override
34 public void clear()
35 {
36 delegate.removeAll();
37 }
38
39 @Override
40 public boolean isLocal()
41 {
42 return true;
43 }
44
45 @Override
46 public boolean containsKey(@Nonnull K key)
47 {
48 return delegate.get(key).isPresent();
49 }
50
51 @Nonnull
52 @Override
53 public Collection<K> getKeys()
54 {
55 return delegate.getKeys();
56 }
57
58 @Nullable
59 @Override
60 public V get(@Nonnull K key)
61 {
62 if (cacheLoader == null)
63 {
64 return delegate.get(key).orElse(null);
65 }
66 else
67 {
68 return delegate.get(key, () -> cacheLoader.load(key));
69 }
70 }
71
72 @Nonnull
73 @Override
74 public V get(@Nonnull K key, @Nonnull Supplier<? extends V> valueSupplier)
75 {
76 return delegate.get(key, valueSupplier::get);
77 }
78
79 @Override
80 public void put(@Nonnull K key, @Nonnull V value)
81 {
82 delegate.put(key, value);
83 }
84
85 @Nullable
86 @Override
87 public V putIfAbsent(@Nonnull K key, @Nonnull V value)
88 {
89 return delegate.putIfAbsent(key, value).orElse(null);
90 }
91
92 @Override
93 public void remove(@Nonnull K key)
94 {
95 delegate.remove(key);
96 }
97
98 @Override
99 public boolean remove(@Nonnull K key, @Nonnull V value)
100 {
101 return delegate.removeIf(key, value);
102 }
103
104 @Override
105 public void removeAll()
106 {
107 delegate.removeAll();
108 }
109
110 @Override
111 public boolean replace(@Nonnull K key, @Nonnull V oldValue, @Nonnull V newValue)
112 {
113 return delegate.replaceIf(key, oldValue, newValue);
114 }
115
116 @Override
117 public void addListener(@Nonnull CacheEntryListener<K, V> listener, boolean includeValues)
118 {
119 throw new UnsupportedOperationException("Unsupported when using the VCache implementation");
120 }
121
122 @Override
123 public void removeListener(@Nonnull CacheEntryListener<K, V> listener)
124 {
125 throw new UnsupportedOperationException("Unsupported when using the VCache implementation");
126 }
127 }