1 package com.atlassian.cache.ehcache;
2
3 import com.atlassian.cache.CacheException;
4 import com.atlassian.cache.CacheSettings;
5 import com.atlassian.cache.CachedReference;
6 import com.atlassian.cache.Supplier;
7 import com.atlassian.cache.impl.ReferenceKey;
8 import net.sf.ehcache.Ehcache;
9 import net.sf.ehcache.Element;
10 import net.sf.ehcache.loader.CacheLoader;
11
12 import javax.annotation.Nullable;
13
14
15
16
17
18
19 class DelegatingCachedReference<V> extends ManagedCacheSupport implements CachedReference<V>
20 {
21 private final Ehcache delegate;
22 private final CacheLoader cacheLoader;
23
24 private DelegatingCachedReference(final Ehcache delegate, final Supplier<V> supplier, CacheSettings settings)
25 {
26 super(delegate, settings);
27 this.delegate = delegate;
28 cacheLoader = new ReferenceCacheLoader<V>(supplier);
29 }
30
31 static <V> DelegatingCachedReference<V> create(final Ehcache delegate, final Supplier<V> supplier, CacheSettings settings)
32 {
33 return new DelegatingCachedReference<V>(delegate, supplier, settings);
34 }
35
36 @SuppressWarnings("unchecked")
37 @Override
38 public V get()
39 {
40 try
41 {
42 Element element = delegate.getWithLoader(ReferenceKey.KEY, cacheLoader, null);
43 return element == null ? null : (V) element.getObjectValue();
44 }
45 catch (net.sf.ehcache.CacheException e)
46 {
47 throw new CacheException(e.getCause());
48 }
49 catch (Exception e)
50 {
51 throw new CacheException(e);
52 }
53 }
54
55 @Override
56 public void reset()
57 {
58 try
59 {
60 delegate.remove(ReferenceKey.KEY);
61 }
62 catch (Exception e)
63 {
64 throw new CacheException(e);
65 }
66 }
67
68 @Override
69 public void clear()
70 {
71 reset();
72 }
73
74 public boolean equals(@Nullable final Object other)
75 {
76 if (other instanceof DelegatingCachedReference)
77 {
78 DelegatingCachedReference otherDelegatingReference = (DelegatingCachedReference) other;
79 if (delegate.equals(otherDelegatingReference.delegate))
80 {
81 return true;
82 }
83 }
84 return false;
85 }
86
87 @Override
88 public int hashCode()
89 {
90 return 3 + delegate.hashCode();
91 }
92
93 }