KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > google > inject > util > ReferenceCache


1 /**
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
17 package com.google.inject.util;
18
19 import static com.google.inject.util.ReferenceType.STRONG;
20
21 /**
22  * Extends {@link ReferenceMap} to support lazy loading values by overriding
23  * {@link #create(Object)}.
24  *
25  * @author crazybob@google.com (Bob Lee)
26  */

27 public abstract class ReferenceCache<K, V>
28     extends AbstractReferenceCache<K, V> {
29
30   private static final long serialVersionUID = 0;
31
32   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
52   V create(FutureValue<V> futureValue, K key) {
53     return create(key);
54   }
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   }
72 }
Popular Tags