1 package com.atlassian.cache.memory;
2
3 import com.atlassian.cache.Cache;
4 import com.atlassian.cache.CacheException;
5 import com.atlassian.cache.CacheSettings;
6 import com.google.common.collect.ComputationException;
7
8 import java.util.Collection;
9 import java.util.concurrent.ConcurrentMap;
10 import javax.annotation.Nullable;
11
12
13
14
15
16
17 class DelegatingCache<K, V> extends ManagedCacheSupport implements Cache<K, V>
18 {
19 private final ConcurrentMap<K, V> internalCache;
20
21 private DelegatingCache(final ConcurrentMap<K, V> internalCache, String name, CacheSettings settings)
22 {
23 super(name, settings);
24 this.internalCache = internalCache;
25 }
26
27 static <K, V> DelegatingCache<K, V> create(final ConcurrentMap<K, V> internalCache, String name, CacheSettings settings)
28 {
29 return new DelegatingCache<K, V>(internalCache, name, settings);
30 }
31
32 @Override
33 public Collection<K> getKeys()
34 {
35 try
36 {
37 return internalCache.keySet();
38 }
39 catch (Exception e)
40 {
41 throw new CacheException(e);
42 }
43 }
44
45 @Override
46 public void put(final K key, final V value)
47 {
48 try
49 {
50 internalCache.put(key, value);
51 }
52 catch (Exception e)
53 {
54 throw new CacheException(e);
55 }
56 }
57
58 @Override
59 public V get(final K key)
60 {
61 try
62 {
63 return internalCache.get(key);
64 }
65 catch (ComputationException e)
66 {
67 throw new CacheException(e.getCause());
68 }
69 catch (Exception e)
70 {
71 throw new CacheException(e);
72 }
73 }
74
75 @Override
76 public void remove(final K key)
77 {
78 try
79 {
80 internalCache.remove(key);
81 }
82 catch (Exception e)
83 {
84 throw new CacheException(e);
85 }
86 }
87
88 @Override
89 public void removeAll()
90 {
91 try
92 {
93 internalCache.clear();
94 }
95 catch (Exception e)
96 {
97 throw new CacheException(e);
98 }
99 }
100
101 @Override
102 public V putIfAbsent(K key, V value)
103 {
104 try
105 {
106 return internalCache.putIfAbsent(key, value);
107 }
108 catch (Exception e)
109 {
110 throw new CacheException(e);
111 }
112 }
113
114 @Override
115 public boolean remove(K key, V value)
116 {
117 try
118 {
119 return internalCache.remove(key, value);
120 }
121 catch (Exception e)
122 {
123 throw new CacheException(e);
124 }
125 }
126
127 @Override
128 public boolean replace(K key, V oldValue, V newValue)
129 {
130 try
131 {
132 return internalCache.replace(key, oldValue, newValue);
133 }
134 catch (Exception e)
135 {
136 throw new CacheException(e);
137 }
138 }
139
140 @Override
141 public void clear()
142 {
143 removeAll();
144 }
145
146 @Override
147 public boolean equals(@Nullable final Object other)
148 {
149 if (other instanceof DelegatingCache)
150 {
151 DelegatingCache otherDelegatingCache = (DelegatingCache) other;
152 if (internalCache.equals(otherDelegatingCache.internalCache))
153 {
154 return true;
155 }
156 }
157 return false;
158 }
159
160 @Override
161 public int hashCode()
162 {
163 return 3 + internalCache.hashCode();
164 }
165 }