01: /*
02: * Licensed to the Apache Software Foundation (ASF) under one or more
03: * contributor license agreements. See the NOTICE file distributed with
04: * this work for additional information regarding copyright ownership.
05: * The ASF licenses this file to You under the Apache License, Version 2.0
06: * (the "License"); you may not use this file except in compliance with
07: * the License. You may obtain a copy of the License at
08: *
09: * http://www.apache.org/licenses/LICENSE-2.0
10: *
11: * Unless required by applicable law or agreed to in writing, software
12: * distributed under the License is distributed on an "AS IS" BASIS,
13: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14: * See the License for the specific language governing permissions and
15: * limitations under the License.
16: */
17:
18: /* $Id: PropertyCache.java 563951 2007-08-08 17:37:33Z vhennebert $ */
19:
20: package org.apache.fop.fo.properties;
21:
22: import java.lang.ref.WeakReference;
23: import java.util.Collections;
24: import java.util.Map;
25: import java.util.WeakHashMap;
26:
27: /**
28: * Thin wrapper around a HashMap to implement the property caching idiom
29: * in which a new Property instance is created then tested against cached
30: * instances created previously. If an existing property is found, this is
31: * retained and the newly created one is instantly eligible for garbage
32: * collection.
33: */
34: public class PropertyCache {
35:
36: private Map propCache = Collections
37: .synchronizedMap(new WeakHashMap());
38:
39: /**
40: * Checks if the given property is present in the cache - if so, returns
41: * a reference to the cached value. Otherwise the given object is added
42: * to the cache and returned.
43: * @param obj
44: * @return the cached instance
45: */
46: public Property fetch(Property prop) {
47:
48: WeakReference ref = (WeakReference) propCache.get(prop);
49: if (ref != null) {
50: Property cacheEntry = (Property) ref.get();
51: if (cacheEntry != null) {
52: return cacheEntry;
53: }
54: }
55: propCache.put(prop, new WeakReference(prop));
56: return prop;
57: }
58: }
|