    001/*
    002 * Licensed to the Apache Software Foundation (ASF) under one or more
    003 * contributor license agreements.  See the NOTICE file distributed with
    004 * this work for additional information regarding copyright ownership.
    005 * The ASF licenses this file to You under the Apache License, Version 2.0
    006 * (the "License"); you may not use this file except in compliance with
    007 * the License.  You may obtain a copy of the License at
    008 *
    009 *      http://www.apache.org/licenses/LICENSE-2.0
    010 *
    011 * Unless required by applicable law or agreed to in writing, software
    012 * distributed under the License is distributed on an "AS IS" BASIS,
    013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    014 * See the License for the specific language governing permissions and
    015 * limitations under the License.
    016 */
    017package org.apache.commons.collections4.map;
    018
    019import java.io.IOException;
    020import java.io.ObjectInputStream;
    021import java.io.ObjectOutputStream;
    022import java.io.Serializable;
    023
    024/**
    025 * A {@code Map} implementation that allows mappings to be
    026 * removed by the garbage collector.
    027 * <p>
    028 * When you construct a {@code ReferenceMap}, you can specify what kind
    029 * of references are used to store the map's keys and values.
    030 * If non-hard references are used, then the garbage collector can remove
    031 * mappings if a key or value becomes unreachable, or if the JVM's memory is
    032 * running low. For information on how the different reference types behave,
    033 * see {@link java.lang.ref.Reference Reference}.
    034 * </p>
    035 * <p>
    036 * Different types of references can be specified for keys and values.
    037 * The keys can be configured to be weak but the values hard,
    038 * in which case this class will behave like a
    039 * <a href="https://docs.oracle.com/javase/8/docs/api/java/util/WeakHashMap.html">
    040 * {@code WeakHashMap}</a>. However, you can also specify hard keys and
    041 * weak values, or any other combination. The default constructor uses
    042 * hard keys and soft values, providing a memory-sensitive cache.
    043 * </p>
    044 * <p>
    045 * This map is similar to
    046 * {@link org.apache.commons.collections4.map.ReferenceIdentityMap ReferenceIdentityMap}.
    047 * It differs in that keys and values in this class are compared using {@code equals()}.
    048 * </p>
    049 * <p>
    050 * This {@link java.util.Map Map} implementation does <em>not</em> allow null elements.
    051 * Attempting to add a null key or value to the map will raise a {@code NullPointerException}.
    052 * </p>
    053 * <p>
    054 * This implementation is not synchronized.
    055 * You can use {@link java.util.Collections#synchronizedMap} to
    056 * provide synchronized access to a {@code ReferenceMap}.
    057 * Remember that synchronization will not stop the garbage collector removing entries.
    058 * </p>
    059 * <p>
    060 * All the available iterators can be reset back to the start by casting to
    061 * {@code ResettableIterator} and calling {@code reset()}.
    062 * </p>
    063 * <p>
    064 * <strong>Note that ReferenceMap is not synchronized and is not thread-safe.</strong>
    065 * If you wish to use this map from multiple threads concurrently, you must use
    066 * appropriate synchronization. The simplest approach is to wrap this map
    067 * using {@link java.util.Collections#synchronizedMap}. This class may throw
    068 * exceptions when accessed by concurrent threads without synchronization.
    069 * </p>
    070 * <p>
    071 * NOTE: As from Commons Collections 3.1 this map extends {@code AbstractReferenceMap}
    072 * (previously it extended AbstractMap). As a result, the implementation is now
    073 * extensible and provides a {@code MapIterator}.
    074 * </p>
    075 *
    076 * @param <K> the type of the keys in the map
    077 * @param <V> the type of the values in the map
    078 * @see java.lang.ref.Reference
    079 * @since 3.0 (previously in main package v2.1)
    080 */
    081public class ReferenceMap<K, V> extends AbstractReferenceMap<K, V> implements Serializable {
    082
    083    /** Serialization version */
    084    private static final long serialVersionUID = 1555089888138299607L;
    085
    086    /**
    087     * Constructs a new {@code ReferenceMap} that will
    088     * use hard references to keys and soft references to values.
    089     */
    090    public ReferenceMap() {
    091        super(ReferenceStrength.HARD, ReferenceStrength.SOFT, DEFAULT_CAPACITY,
    092                DEFAULT_LOAD_FACTOR, false);
    093    }
    094
    095    /**
    096     * Constructs a new {@code ReferenceMap} that will
    097     * use the specified types of references.
    098     *
    099     * @param keyType  the type of reference to use for keys;
    100     *   must be {@link AbstractReferenceMap.ReferenceStrength#HARD HARD},
    101     *   {@link AbstractReferenceMap.ReferenceStrength#SOFT SOFT},
    102     *   {@link AbstractReferenceMap.ReferenceStrength#WEAK WEAK}
    103     * @param valueType  the type of reference to use for values;
    104     *   must be {@link AbstractReferenceMap.ReferenceStrength#HARD HARD},
    105     *   {@link AbstractReferenceMap.ReferenceStrength#SOFT SOFT},
    106     *   {@link AbstractReferenceMap.ReferenceStrength#WEAK WEAK}
    107     */
    108    public ReferenceMap(final ReferenceStrength keyType, final ReferenceStrength valueType) {
    109        super(keyType, valueType, DEFAULT_CAPACITY, DEFAULT_LOAD_FACTOR, false);
    110    }
    111
    112    /**
    113     * Constructs a new {@code ReferenceMap} that will
    114     * use the specified types of references.
    115     *
    116     * @param keyType  the type of reference to use for keys;
    117     *   must be {@link AbstractReferenceMap.ReferenceStrength#HARD HARD},
    118     *   {@link AbstractReferenceMap.ReferenceStrength#SOFT SOFT},
    119     *   {@link AbstractReferenceMap.ReferenceStrength#WEAK WEAK}
    120     * @param valueType  the type of reference to use for values;
    121     *   must be {@link AbstractReferenceMap.ReferenceStrength#HARD HARD},
    122     *   {@link AbstractReferenceMap.ReferenceStrength#SOFT SOFT},
    123     *   {@link AbstractReferenceMap.ReferenceStrength#WEAK WEAK}
    124     * @param purgeValues should the value be automatically purged when the
    125     *   key is garbage collected
    126     */
    127    public ReferenceMap(final ReferenceStrength keyType, final ReferenceStrength valueType, final boolean purgeValues) {
    128        super(keyType, valueType, DEFAULT_CAPACITY, DEFAULT_LOAD_FACTOR, purgeValues);
    129    }
    130
    131    /**
    132     * Constructs a new {@code ReferenceMap} with the
    133     * specified reference types, load factor and initial
    134     * capacity.
    135     *
    136     * @param keyType  the type of reference to use for keys;
    137     *   must be {@link AbstractReferenceMap.ReferenceStrength#HARD HARD},
    138     *   {@link AbstractReferenceMap.ReferenceStrength#SOFT SOFT},
    139     *   {@link AbstractReferenceMap.ReferenceStrength#WEAK WEAK}
    140     * @param valueType  the type of reference to use for values;
    141     *   must be {@link AbstractReferenceMap.ReferenceStrength#HARD HARD},
    142     *   {@link AbstractReferenceMap.ReferenceStrength#SOFT SOFT},
    143     *   {@link AbstractReferenceMap.ReferenceStrength#WEAK WEAK}
    144     * @param capacity  the initial capacity for the map
    145     * @param loadFactor  the load factor for the map
    146     */
    147    public ReferenceMap(final ReferenceStrength keyType, final ReferenceStrength valueType, final int capacity,
    148            final float loadFactor) {
    149        super(keyType, valueType, capacity, loadFactor, false);
    150    }
    151
    152    /**
    153     * Constructs a new {@code ReferenceMap} with the
    154     * specified reference types, load factor and initial
    155     * capacity.
    156     *
    157     * @param keyType  the type of reference to use for keys;
    158     *   must be {@link AbstractReferenceMap.ReferenceStrength#HARD HARD},
    159     *   {@link AbstractReferenceMap.ReferenceStrength#SOFT SOFT},
    160     *   {@link AbstractReferenceMap.ReferenceStrength#WEAK WEAK}
    161     * @param valueType  the type of reference to use for values;
    162     *   must be {@link AbstractReferenceMap.ReferenceStrength#HARD HARD},
    163     *   {@link AbstractReferenceMap.ReferenceStrength#SOFT SOFT},
    164     *   {@link AbstractReferenceMap.ReferenceStrength#WEAK WEAK}
    165     * @param capacity  the initial capacity for the map
    166     * @param loadFactor  the load factor for the map
    167     * @param purgeValues  should the value be automatically purged when the
    168     *   key is garbage collected
    169     */
    170    public ReferenceMap(final ReferenceStrength keyType, final ReferenceStrength valueType, final int capacity,
    171            final float loadFactor, final boolean purgeValues) {
    172        super(keyType, valueType, capacity, loadFactor, purgeValues);
    173    }
    174
    175    /**
    176     * Deserializes the map in using a custom routine.
    177     *
    178     * @param in the input stream
    179     * @throws IOException if an error occurs while reading from the stream
    180     * @throws ClassNotFoundException if an object read from the stream cannot be loaded
    181     */
    182    private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
    183        in.defaultReadObject();
    184        doReadObject(in);
    185    }
    186
    187    /**
    188     * Serializes this object to an ObjectOutputStream.
    189     *
    190     * @param out the target ObjectOutputStream.
    191     * @throws IOException thrown when an I/O errors occur writing to the target stream.
    192     */
    193    private void writeObject(final ObjectOutputStream out) throws IOException {
    194        out.defaultWriteObject();
    195        doWriteObject(out);
    196    }
    197
    198}