1 | |
|
2 | |
|
3 | |
|
4 | |
|
5 | |
|
6 | |
|
7 | |
|
8 | |
|
9 | |
|
10 | |
|
11 | |
|
12 | |
|
13 | |
|
14 | |
|
15 | |
|
16 | |
package org.apache.commons.cache; |
17 | |
|
18 | |
import java.util.HashMap; |
19 | |
import java.io.Serializable; |
20 | |
|
21 | |
|
22 | |
|
23 | |
|
24 | |
|
25 | |
|
26 | |
public class MemoryStash extends BaseStash implements Stash { |
27 | 0 | protected HashMap _hash = null; |
28 | 0 | protected int _maxObjs = 1000; |
29 | 0 | protected Cache _cache = null; |
30 | |
|
31 | 0 | public MemoryStash(int maxobjs) { |
32 | 0 | _maxObjs = maxobjs; |
33 | 0 | _hash = new HashMap(); |
34 | 0 | } |
35 | |
|
36 | |
public synchronized int canStore(Serializable key, Serializable val, Long expiresAt, Long cost, Serializable group, byte[] serialized) { |
37 | 0 | if(_hash.size() < _maxObjs) { |
38 | 0 | return Stash.YES; |
39 | |
} else { |
40 | 0 | return Stash.NO_FULL; |
41 | |
} |
42 | |
} |
43 | |
|
44 | |
public synchronized boolean store(Serializable key, Serializable val, Long expiresAt, Long cost, Serializable group, byte[] serialized) { |
45 | |
try { |
46 | 0 | _hash.put(key,new CachedObjectInfoImpl(val,expiresAt,cost)); |
47 | 0 | } catch(Exception e) { |
48 | 0 | return false; |
49 | 0 | } |
50 | 0 | return true; |
51 | |
} |
52 | |
|
53 | |
public Serializable retrieve(Serializable key) { |
54 | |
|
55 | 0 | synchronized(_cache) { |
56 | 0 | synchronized(this) { |
57 | 0 | CachedObjectInfo info = (CachedObjectInfo)(_hash.get(key)); |
58 | 0 | if(null != info) { |
59 | 0 | Long expiry = info.getExpirationTs(); |
60 | 0 | if(null != expiry) { |
61 | 0 | if(expiry.longValue() < System.currentTimeMillis()) { |
62 | 0 | _cache.clear(key); |
63 | 0 | return null; |
64 | |
} else { |
65 | 0 | return info.getKey(); |
66 | |
} |
67 | |
} else { |
68 | 0 | return info.getKey(); |
69 | |
} |
70 | |
} else { |
71 | 0 | return null; |
72 | |
} |
73 | 0 | } |
74 | 0 | } |
75 | |
} |
76 | |
|
77 | |
public boolean contains(Serializable key) { |
78 | 0 | return _hash.containsKey(key); |
79 | |
} |
80 | |
|
81 | |
public synchronized float capacity() { |
82 | 0 | return (((float)_hash.size())/((float)_maxObjs)); |
83 | |
} |
84 | |
|
85 | |
public void clear(Serializable key) { |
86 | 0 | _hash.remove(key); |
87 | 0 | } |
88 | |
|
89 | |
public synchronized void clear() { |
90 | 0 | _hash.clear(); |
91 | 0 | } |
92 | |
|
93 | |
public void setCache(Cache c) { |
94 | 0 | if(null != _cache) { |
95 | 0 | Object mutex = _cache; |
96 | 0 | synchronized(mutex) { |
97 | 0 | synchronized(this) { |
98 | 0 | unsetCache(); |
99 | 0 | _cache = c; |
100 | 0 | } |
101 | 0 | } |
102 | 0 | } else { |
103 | 0 | _cache = c; |
104 | |
} |
105 | 0 | } |
106 | |
|
107 | |
public void unsetCache() { |
108 | 0 | if(null != _cache) { |
109 | 0 | Object mutex = _cache; |
110 | 0 | synchronized(mutex) { |
111 | 0 | clear(); |
112 | 0 | _cache = null; |
113 | 0 | } |
114 | |
} |
115 | 0 | } |
116 | |
} |