01: /*
02: * @(#)ResourceCache.java 1.2 04/12/06
03: *
04: * Copyright (c) 2002-2004 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 org.pnuts.lib;
10:
11: import java.util.*;
12: import java.lang.ref.*;
13:
14: /**
15: * Resource cache implemented with SoftReference.
16: */
17: class ResourceCache {
18:
19: final static Object NULL = new Object();
20:
21: WeakHashMap resources = new WeakHashMap();
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 synchronized Object findResource(Object key) {
37: if (key == null) {
38: key = NULL;
39: }
40: SoftReference ref = (SoftReference) resources.get(key);
41: if (ref != null) {
42: return ref.get();
43: } else {
44: return null;
45: }
46: }
47:
48: /**
49: * Creates a new resource associated with the specified key.
50: *
51: * @param key the key of the resource
52: * @return a newly created resource
53: */
54: protected Object createResource(Object key) {
55: return null;
56: }
57:
58: /**
59: * Gets a resource associated with the specified key.
60: * If the resource has been expired, a new one is created.
61: *
62: * @param key the key of the resource
63: * @return a resource associated with the key
64: */
65: public Object getResource(Object key) {
66: Object resource = findResource(key);
67: if (resource == null) {
68: resource = createResource(key);
69: if (key == null) {
70: key = NULL;
71: }
72: resources.put(key, new SoftReference(resource));
73: }
74: return resource;
75: }
76:
77: /**
78: * Invalidate the resource associated with the specified key
79: */
80: public synchronized void invalidate(Object key) {
81: resources.remove(key);
82: }
83:
84: /**
85: * Discard all cached resources
86: */
87: public synchronized void reset() {
88: resources.clear();
89: }
90: }
|