01: /*
02: * User: Michael Rettig
03: * Date: Aug 12, 2002
04: * Time: 4:13:25 PM
05: */
06: package net.sourceforge.jaxor.impl;
07:
08: import net.sourceforge.jaxor.PrimaryKeySet;
09: import net.sourceforge.jaxor.api.EntityInterface;
10: import net.sourceforge.jaxor.api.InstanceCache;
11:
12: import java.io.Serializable;
13: import java.util.HashMap;
14: import java.util.Map;
15:
16: public class InstanceCacheImpl implements InstanceCache {
17:
18: /**
19: * Use a Map because we need to get original instance from the map. No simple way to do this with Set
20: */
21: private final Map _cache = new HashMap(5000);
22:
23: public void remove(EntityInterface abstractEntity) {
24: _cache.remove(new CacheKey(abstractEntity));
25: }
26:
27: /**
28: * In most cases we are just going to put the entity in the cache, and replace nothing. This is the most
29: * common behavior so we optimize for this case. In the case where we've loaded this object before, we
30: * pay the extra cost of popping the cached version, then recaching.
31: */
32: public EntityInterface updateCache(EntityInterface result) {
33: CacheKey key = new CacheKey(result);
34: EntityInterface priorCache = (EntityInterface) _cache.put(key,
35: result);
36: if (priorCache == null)
37: return result;
38: _cache.put(key, priorCache);
39: return priorCache;
40: }
41:
42: public EntityInterface getFromCache(Class _implClass,
43: PrimaryKeySet pk) {
44: return (EntityInterface) _cache
45: .get(new CacheKey(_implClass, pk));
46: }
47:
48: public void clear() {
49: _cache.clear();
50: }
51:
52: private static class CacheKey implements Serializable {
53: private final Class _implClass;
54: private final PrimaryKeySet _pk;
55:
56: public CacheKey(Class implClass, PrimaryKeySet pk) {
57: _implClass = implClass;
58: _pk = pk;
59: }
60:
61: public CacheKey(EntityInterface entity) {
62: _implClass = entity.getImplementationClass();
63: _pk = entity.getPrimaryKeySet();
64: }
65:
66: public int hashCode() {
67: return _pk.hashCode();
68: }
69:
70: public boolean equals(Object obj) {
71: if (obj == null)
72: return false;
73: if (obj.getClass().equals(getClass()))
74: return equals((CacheKey) obj);
75: return false;
76: }
77:
78: public boolean equals(CacheKey key) {
79: return key._implClass.equals(_implClass)
80: && key._pk.equals(_pk);
81: }
82: }
83: }
|