01: /*
02: * @(#)ResourceCache.java 1.2 04/12/06
03: *
04: * Copyright (c) 2002,2003 Sun Microsystems, Inc. All Rights Reserved.
05: *
06: * See the file "LICENSE.txt" for information on usage and redistribution
07: * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
08: */
09: package pnuts.lib;
10:
11: import java.util.*;
12: import org.pnuts.util.LRUCache;
13:
14: /**
15: * Resource cache implemented with LRU cache
16: */
17: class ResourceCache {
18:
19: final static Object NULL = new Object();
20:
21: LRUCache resources = new LRUCache(64);
22:
23: /**
24: * Constructor
25: */
26: public ResourceCache() {
27: }
28:
29: /**
30: * Finds a resource associated with the specified key.
31: * Returns null if not found or already expired.
32: *
33: * @param key the key of the resource
34: * @return the resource or null
35: */
36: protected Object findResource(Object key) {
37: if (key == null) {
38: key = NULL;
39: }
40: return resources.get(key);
41: }
42:
43: /**
44: * Creates a new resource associated with the specified key.
45: *
46: * @param key the key of the resource
47: * @return a newly created resource
48: */
49: protected Object createResource(Object key) {
50: return null;
51: }
52:
53: /**
54: * Gets a resource associated with the specified key.
55: * If the resource has been expired, a new one is created.
56: *
57: * @param key the key of the resource
58: * @return a resource associated with the key
59: */
60: public Object getResource(Object key) {
61: Object resource = findResource(key);
62: if (resource == null) {
63: resource = createResource(key);
64: if (key == null) {
65: key = NULL;
66: }
67: resources.put(key, resource);
68: }
69: return resource;
70: }
71:
72: /**
73: * Discard all cached resources
74: */
75: public void reset() {
76: resources.reset();
77: }
78: }
|