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: * $Header:$
18: */
19: package org.apache.beehive.netui.util.internal.cache;
20:
21: import java.util.Map;
22: import org.apache.beehive.netui.util.internal.concurrent.InternalConcurrentHashMap;
23:
24: /**
25: * Thread-safe cache that is stored statically per-Class.
26: */
27: public final class ClassLevelCache {
28:
29: private static InternalConcurrentHashMap _classCaches = new InternalConcurrentHashMap();
30: private InternalConcurrentHashMap _caches = new InternalConcurrentHashMap();
31:
32: public static ClassLevelCache getCache(Class c) {
33: String className = c.getName();
34: ClassLevelCache cache = (ClassLevelCache) _classCaches
35: .get(className);
36:
37: if (cache == null) {
38: cache = new ClassLevelCache();
39: _classCaches.put(className, cache);
40: }
41:
42: return cache;
43: }
44:
45: protected ClassLevelCache() {
46: }
47:
48: public Object get(String majorKey, String minorKey) {
49: InternalConcurrentHashMap cache = (InternalConcurrentHashMap) _caches
50: .get(majorKey);
51: return cache != null ? cache.get(minorKey) : null;
52: }
53:
54: public Object getCacheObject(String cacheID) {
55: return _caches.get(cacheID);
56: }
57:
58: public void setCacheObject(String cacheID, Object object) {
59: _caches.put(cacheID, object);
60: }
61:
62: public Map getCacheMap(String cacheID) {
63: return getCacheMap(cacheID, true);
64: }
65:
66: public Map getCacheMap(String cacheID, boolean createIfMissing) {
67: InternalConcurrentHashMap cache = (InternalConcurrentHashMap) _caches
68: .get(cacheID);
69:
70: if (cache == null && createIfMissing) {
71: cache = new InternalConcurrentHashMap();
72: _caches.put(cacheID, cache);
73: }
74:
75: return cache;
76: }
77:
78: public void put(String cacheID, String minorKey, Object value) {
79: //
80: // ConcurrentHashMap can't accept null. For now we'll just assert; if it becomes necessary to add null,
81: // then we can use a marker value.
82: //
83: assert value != null;
84: getCacheMap(cacheID).put(minorKey, value);
85: }
86:
87: public static void clearAll() {
88: _classCaches.clear();
89: }
90: }
|