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 protected HashMap _hash = null;
28 protected int _maxObjs = 1000;
29 protected Cache _cache = null;
30
31 public MemoryStash(int maxobjs) {
32 _maxObjs = maxobjs;
33 _hash = new HashMap();
34 }
35
36 public synchronized int canStore(Serializable key, Serializable val, Long expiresAt, Long cost, Serializable group, byte[] serialized) {
37 if(_hash.size() < _maxObjs) {
38 return Stash.YES;
39 } else {
40 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 _hash.put(key,new CachedObjectInfoImpl(val,expiresAt,cost));
47 } catch(Exception e) {
48 return false;
49 }
50 return true;
51 }
52
53 public Serializable retrieve(Serializable key) {
54
55 synchronized(_cache) {
56 synchronized(this) {
57 CachedObjectInfo info = (CachedObjectInfo)(_hash.get(key));
58 if(null != info) {
59 Long expiry = info.getExpirationTs();
60 if(null != expiry) {
61 if(expiry.longValue() < System.currentTimeMillis()) {
62 _cache.clear(key);
63 return null;
64 } else {
65 return info.getKey();
66 }
67 } else {
68 return info.getKey();
69 }
70 } else {
71 return null;
72 }
73 }
74 }
75 }
76
77 public boolean contains(Serializable key) {
78 return _hash.containsKey(key);
79 }
80
81 public synchronized float capacity() {
82 return (((float)_hash.size())/((float)_maxObjs));
83 }
84
85 public void clear(Serializable key) {
86 _hash.remove(key);
87 }
88
89 public synchronized void clear() {
90 _hash.clear();
91 }
92
93 public void setCache(Cache c) {
94 if(null != _cache) {
95 Object mutex = _cache;
96 synchronized(mutex) {
97 synchronized(this) {
98 unsetCache();
99 _cache = c;
100 }
101 }
102 } else {
103 _cache = c;
104 }
105 }
106
107 public void unsetCache() {
108 if(null != _cache) {
109 Object mutex = _cache;
110 synchronized(mutex) {
111 clear();
112 _cache = null;
113 }
114 }
115 }
116 }