blob: 85b3285a3e3790f48da8f6a918afd7d7ce6afca6 [file] [log] [blame]
crazyboblee66b415a2006-08-25 02:01:19 +00001/**
2 * Copyright (C) 2006 Google Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
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 */
16
kevinb9ncad2c2b2007-05-15 17:28:03 +000017package com.google.inject.internal;
crazyboblee66b415a2006-08-25 02:01:19 +000018
kevinb9ncad2c2b2007-05-15 17:28:03 +000019import static com.google.inject.internal.ReferenceType.STRONG;
crazyboblee66b415a2006-08-25 02:01:19 +000020
crazyboblee66b415a2006-08-25 02:01:19 +000021/**
22 * Extends {@link ReferenceMap} to support lazy loading values by overriding
23 * {@link #create(Object)}.
24 *
25 * @author crazybob@google.com (Bob Lee)
26 */
crazyboblee07e41822006-11-21 01:27:08 +000027public abstract class ReferenceCache<K, V>
28 extends AbstractReferenceCache<K, V> {
crazyboblee66b415a2006-08-25 02:01:19 +000029
30 private static final long serialVersionUID = 0;
31
crazyboblee66b415a2006-08-25 02:01:19 +000032 public ReferenceCache(ReferenceType keyReferenceType,
33 ReferenceType valueReferenceType) {
34 super(keyReferenceType, valueReferenceType);
35 }
36
37 /**
38 * Equivalent to {@code new ReferenceCache(STRONG, STRONG)}.
39 */
40 public ReferenceCache() {
41 super(STRONG, STRONG);
42 }
43
44 /**
45 * Override to lazy load values. Use as an alternative to {@link
46 * #put(Object,Object)}. Invoked by getter if value isn't already cached.
47 * Must not return {@code null}. This method will not be called again until
48 * the garbage collector reclaims the returned value.
49 */
50 protected abstract V create(K key);
51
crazyboblee07e41822006-11-21 01:27:08 +000052 V create(FutureValue<V> futureValue, K key) {
53 return create(key);
crazyboblee66b415a2006-08-25 02:01:19 +000054 }
55
56 /**
57 * Returns a {@code ReferenceCache} delegating to the specified {@code
58 * function}. The specified function must not return {@code null}.
59 */
60 public static <K, V> ReferenceCache<K, V> of(
61 ReferenceType keyReferenceType,
62 ReferenceType valueReferenceType,
63 final Function<? super K, ? extends V> function) {
64 ensureNotNull(function);
65 return new ReferenceCache<K, V>(keyReferenceType, valueReferenceType) {
66 protected V create(K key) {
67 return function.apply(key);
68 }
69 private static final long serialVersionUID = 0;
70 };
71 }
crazyboblee07e41822006-11-21 01:27:08 +000072}