View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      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  package org.apache.commons.collections4.map;
18  
19  import java.io.IOException;
20  import java.io.ObjectInputStream;
21  import java.io.ObjectOutputStream;
22  import java.io.Serializable;
23  import java.lang.ref.Reference;
24  
25  /**
26   * A {@code Map} implementation that allows mappings to be
27   * removed by the garbage collector and matches keys and values based
28   * on {@code ==} not {@code equals()}.
29   * <p>
30   * When you construct a {@code ReferenceIdentityMap}, you can specify what kind
31   * of references are used to store the map's keys and values.
32   * If non-hard references are used, then the garbage collector can remove
33   * mappings if a key or value becomes unreachable, or if the JVM's memory is
34   * running low. For information on how the different reference types behave,
35   * see {@link Reference}.
36   * </p>
37   * <p>
38   * Different types of references can be specified for keys and values.
39   * The default constructor uses hard keys and soft values, providing a
40   * memory-sensitive cache.
41   * </p>
42   * <p>
43   * This map is similar to
44   * {@link org.apache.commons.collections4.map.ReferenceMap ReferenceMap}.
45   * It differs in that keys and values in this class are compared using {@code ==}.
46   * </p>
47   * <p>
48   * This map will violate the detail of various Map and map view contracts.
49   * As a general rule, don't compare this map to other maps.
50   * </p>
51   * <p>
52   * This {@link java.util.Map Map} implementation does <em>not</em> allow null elements.
53   * Attempting to add a null key or value to the map will raise a {@code NullPointerException}.
54   * </p>
55   * <p>
56   * This implementation is not synchronized.
57   * You can use {@link java.util.Collections#synchronizedMap} to
58   * provide synchronized access to a {@code ReferenceIdentityMap}.
59   * Remember that synchronization will not stop the garbage collector removing entries.
60   * </p>
61   * <p>
62   * All the available iterators can be reset back to the start by casting to
63   * {@code ResettableIterator} and calling {@code reset()}.
64   * </p>
65   * <p>
66   * <strong>Note that ReferenceIdentityMap is not synchronized and is not thread-safe.</strong>
67   * If you wish to use this map from multiple threads concurrently, you must use
68   * appropriate synchronization. The simplest approach is to wrap this map
69   * using {@link java.util.Collections#synchronizedMap}. This class may throw
70   * exceptions when accessed by concurrent threads without synchronization.
71   * </p>
72   *
73   * @param <K> the type of the keys in this map
74   * @param <V> the type of the values in this map
75   * @see java.lang.ref.Reference
76   * @since 3.0 (previously in main package v2.1)
77   */
78  public class ReferenceIdentityMap<K, V> extends AbstractReferenceMap<K, V> implements Serializable {
79  
80      /** Serialization version */
81      private static final long serialVersionUID = -1266190134568365852L;
82  
83      /**
84       * Constructs a new {@code ReferenceIdentityMap} that will
85       * use hard references to keys and soft references to values.
86       */
87      public ReferenceIdentityMap() {
88          super(ReferenceStrength.HARD, ReferenceStrength.SOFT, DEFAULT_CAPACITY,
89                  DEFAULT_LOAD_FACTOR, false);
90      }
91  
92      /**
93       * Constructs a new {@code ReferenceIdentityMap} that will
94       * use the specified types of references.
95       *
96       * @param keyType  the type of reference to use for keys;
97       *   must be {@link AbstractReferenceMap.ReferenceStrength#HARD HARD},
98       *   {@link AbstractReferenceMap.ReferenceStrength#SOFT SOFT},
99       *   {@link AbstractReferenceMap.ReferenceStrength#WEAK WEAK}
100      * @param valueType  the type of reference to use for values;
101      *   must be {@link AbstractReferenceMap.ReferenceStrength#HARD HARD},
102      *   {@link AbstractReferenceMap.ReferenceStrength#SOFT SOFT},
103      *   {@link AbstractReferenceMap.ReferenceStrength#WEAK WEAK}
104      */
105     public ReferenceIdentityMap(final ReferenceStrength keyType, final ReferenceStrength valueType) {
106         super(keyType, valueType, DEFAULT_CAPACITY, DEFAULT_LOAD_FACTOR, false);
107     }
108 
109     /**
110      * Constructs a new {@code ReferenceIdentityMap} that will
111      * use the specified types of references.
112      *
113      * @param keyType  the type of reference to use for keys;
114      *   must be {@link AbstractReferenceMap.ReferenceStrength#HARD HARD},
115      *   {@link AbstractReferenceMap.ReferenceStrength#SOFT SOFT},
116      *   {@link AbstractReferenceMap.ReferenceStrength#WEAK WEAK}
117      * @param valueType  the type of reference to use for values;
118      *   must be {@link AbstractReferenceMap.ReferenceStrength#HARD HARD},
119      *   {@link AbstractReferenceMap.ReferenceStrength#SOFT SOFT},
120      *   {@link AbstractReferenceMap.ReferenceStrength#WEAK WEAK}
121      * @param purgeValues should the value be automatically purged when the
122      *   key is garbage collected
123      */
124     public ReferenceIdentityMap(final ReferenceStrength keyType, final ReferenceStrength valueType,
125             final boolean purgeValues) {
126         super(keyType, valueType, DEFAULT_CAPACITY, DEFAULT_LOAD_FACTOR, purgeValues);
127     }
128 
129     /**
130      * Constructs a new {@code ReferenceIdentityMap} with the
131      * specified reference types, load factor and initial capacity.
132      *
133      * @param keyType  the type of reference to use for keys;
134      *   must be {@link AbstractReferenceMap.ReferenceStrength#HARD HARD},
135      *   {@link AbstractReferenceMap.ReferenceStrength#SOFT SOFT},
136      *   {@link AbstractReferenceMap.ReferenceStrength#WEAK WEAK}
137      * @param valueType  the type of reference to use for values;
138      *   must be {@link AbstractReferenceMap.ReferenceStrength#HARD HARD},
139      *   {@link AbstractReferenceMap.ReferenceStrength#SOFT SOFT},
140      *   {@link AbstractReferenceMap.ReferenceStrength#WEAK WEAK}
141      * @param capacity  the initial capacity for the map
142      * @param loadFactor  the load factor for the map
143      */
144     public ReferenceIdentityMap(final ReferenceStrength keyType, final ReferenceStrength valueType,
145             final int capacity, final float loadFactor) {
146         super(keyType, valueType, capacity, loadFactor, false);
147     }
148 
149     /**
150      * Constructs a new {@code ReferenceIdentityMap} with the
151      * specified reference types, load factor and initial capacity.
152      *
153      * @param keyType  the type of reference to use for keys;
154      *   must be {@link AbstractReferenceMap.ReferenceStrength#HARD HARD},
155      *   {@link AbstractReferenceMap.ReferenceStrength#SOFT SOFT},
156      *   {@link AbstractReferenceMap.ReferenceStrength#WEAK WEAK}
157      * @param valueType  the type of reference to use for values;
158      *   must be {@link AbstractReferenceMap.ReferenceStrength#HARD HARD},
159      *   {@link AbstractReferenceMap.ReferenceStrength#SOFT SOFT},
160      *   {@link AbstractReferenceMap.ReferenceStrength#WEAK WEAK}
161      * @param capacity  the initial capacity for the map
162      * @param loadFactor  the load factor for the map
163      * @param purgeValues  should the value be automatically purged when the
164      *   key is garbage collected
165      */
166     public ReferenceIdentityMap(final ReferenceStrength keyType, final ReferenceStrength valueType,
167             final int capacity, final float loadFactor, final boolean purgeValues) {
168         super(keyType, valueType, capacity, loadFactor, purgeValues);
169     }
170 
171     /**
172      * Gets the hash code for the key specified.
173      * <p>
174      * This implementation uses the identity hash code.
175      * </p>
176      *
177      * @param key  the key to get a hash code for
178      * @return the hash code
179      */
180     @Override
181     protected int hash(final Object key) {
182         return System.identityHashCode(key);
183     }
184 
185     /**
186      * Gets the hash code for a MapEntry.
187      * <p>
188      * This implementation uses the identity hash code.
189      * </p>
190      *
191      * @param key  the key to get a hash code for, may be null
192      * @param value  the value to get a hash code for, may be null
193      * @return the hash code, as per the MapEntry specification
194      */
195     @Override
196     protected int hashEntry(final Object key, final Object value) {
197         return System.identityHashCode(key) ^
198                System.identityHashCode(value);
199     }
200 
201     /**
202      * Compares two keys for equals.
203      * <p>
204      * This implementation converts the key from the entry to a real reference
205      * before comparison and uses {@code ==}.
206      * </p>
207      *
208      * @param key1  the first key to compare passed in from outside
209      * @param key2  the second key extracted from the entry via {@code entry.key}
210      * @return true if equal by identity
211      */
212     @Override
213     protected boolean isEqualKey(final Object key1, Object key2) {
214         key2 = isKeyType(ReferenceStrength.HARD) ? key2 : ((Reference<?>) key2).get();
215         return key1 == key2;
216     }
217 
218     /**
219      * Compares two values for equals.
220      * <p>
221      * This implementation uses {@code ==}.
222      * </p>
223      *
224      * @param value1  the first value to compare passed in from outside
225      * @param value2  the second value extracted from the entry via {@code getValue()}
226      * @return true if equal by identity
227      */
228     @Override
229     protected boolean isEqualValue(final Object value1, final Object value2) {
230         return value1 == value2;
231     }
232 
233     /**
234      * Deserializes the map in using a custom routine.
235      *
236      * @param in the input stream
237      * @throws IOException if an error occurs while reading from the stream
238      * @throws ClassNotFoundException if an object read from the stream cannot be loaded
239      */
240     private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
241         in.defaultReadObject();
242         doReadObject(in);
243     }
244 
245     /**
246      * Serializes this object to an ObjectOutputStream.
247      *
248      * @param out the target ObjectOutputStream.
249      * @throws IOException thrown when an I/O errors occur writing to the target stream.
250      */
251     private void writeObject(final ObjectOutputStream out) throws IOException {
252         out.defaultWriteObject();
253         doWriteObject(out);
254     }
255 
256 }