01: /**
02: * Copyright (C) 2006 Google Inc.
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS,
12: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13: * See the License for the specific language governing permissions and
14: * limitations under the License.
15: */package com.bm.ejb3guice.internal;
16:
17: import static com.bm.ejb3guice.internal.ReferenceType.STRONG;
18:
19: /**
20: * Extends {@link ReferenceMap} to support lazy loading values by overriding
21: * {@link #create(Object)}.
22: *
23: * @author crazybob@google.com (Bob Lee)
24: */
25: public abstract class ReferenceCache<K, V> extends
26: AbstractReferenceCache<K, V> {
27:
28: private static final long serialVersionUID = 0;
29:
30: public ReferenceCache(ReferenceType keyReferenceType,
31: ReferenceType valueReferenceType) {
32: super (keyReferenceType, valueReferenceType);
33: }
34:
35: /**
36: * Equivalent to {@code new ReferenceCache(STRONG, STRONG)}.
37: */
38: public ReferenceCache() {
39: super (STRONG, STRONG);
40: }
41:
42: /**
43: * Override to lazy load values. Use as an alternative to {@link
44: * #put(Object,Object)}. Invoked by getter if value isn't already cached.
45: * Must not return {@code null}. This method will not be called again until
46: * the garbage collector reclaims the returned value.
47: */
48: protected abstract V create(K key);
49:
50: V create(FutureValue<V> futureValue, K key) {
51: return create(key);
52: }
53:
54: /**
55: * Returns a {@code ReferenceCache} delegating to the specified {@code
56: * function}. The specified function must not return {@code null}.
57: */
58: public static <K, V> ReferenceCache<K, V> of(
59: ReferenceType keyReferenceType,
60: ReferenceType valueReferenceType,
61: final Function<? super K, ? extends V> function) {
62: ensureNotNull(function);
63: return new ReferenceCache<K, V>(keyReferenceType,
64: valueReferenceType) {
65: protected V create(K key) {
66: return function.apply(key);
67: }
68:
69: private static final long serialVersionUID = 0;
70: };
71: }
72: }
|